Saturday, May 9, 2009

Clarify Your Intent

A maintainable unit test suite is essential in making software that will stand the test of time.
However after a while, some tests might get hard to read.
I was working on a flex application lately and was using fluint as my unit test framework. When we could we used the framework to test GUI components.
At some point we had a component that was composed of a text input and a button. For the sake of simplification, let's say that when clicking on the button, a label gets updated.
At first, the test looked like this:
component.input.text = "hello, world!"
component.button.dispatchEvent(new MouseEvent(MouseEvent.CLICK))
assertEquals("hello, world!", component.label.text)
When I read the test this is what went in my mind:
Set the text of the 'input' of the component to 'hello, world!'
Dispatch a mouse event of type click to the component's button
Make sure 'hello, world!' appears in the component's label text
That gave me an headache...
Next I changed the code to:
enterText("hello, world!')
clickOn(button)
assertLabelEquals("hello, world!")
Let's read it outloud again:
Enter text "hello, world!"
Click on the button
Make sure the label equals "hello, world!"
Now whenever someone looks at the test, the intent is a lot clearer. Whenever possible, try to make the test readable for a human being. Tests are part of your code. Written clearly, they document the intent and are a pretty good reference on how to use a class. However it's pretty important to make the test read like a possible user of the class would use it.
The API of the class being tested might be clear enough that you don't have to do anything. If it is not, don't be afraid to create another API in your test to make the intent clearer.

No comments:

Post a Comment