Java Reference
In-Depth Information
You follow the same pattern F as the first method:
1
Insert a statement that should throw an exception.
Add the expected parameter to the @Test annotation to denote what kind of
an exception you expect.
2
Proceed normally.
3
JUnit best practices: make exception tests easy to read
Normally the expected parameter in the @Test annotation clearly tells the devel-
opers that an exception of that type should be raised. But you can go even further.
Besides naming your test methods in an obvious fashion to denote that this method
is testing an exceptional condition, you can also place some comments to high-
light the line of the code that produces the expected exception.
The controller class is by no means finished, but you have a respectable first iteration
and a test suite proving that it works. Now you can commit the controller package,
along with its tests, to the project's code repository and move on to the next task on
your list.
JUnit best practices: let the test improve the code
An easy way to identify exceptional paths is to examine the different branches in
the code you're testing. By branches , we mean the outcome of if clauses, switch
statements, and try-catch blocks. When you start following these branches,
sometimes you may find that testing each alternative is painful. If code is difficult
to test, it's usually just as difficult to use. When testing indicates a poor design
(called a code smell , http://c2.com/cgi/wiki?CodeSmell), you should stop and
refactor the domain code. In the case of too many branches, the solution is usually
to split a larger method into several smaller methods. 5 Alternatively, you may need
to modify the class hierarchy to better represent the problem domain. 6 Other situ-
ations would call for different refactorings.
A test is your code's first “customer,” and as the maxim goes, “the customer is
always right.”
The next task on our list is timeout testing. 5 6
3.4
Timeout testing
So far, we've tested our application for proper functionality—when supplied with the
right data, not only does it behave in the expected manner, but it also produces
5
Fowler, Refactoring , “Extract Method.”
6
More about writing testable code can be found in chapter 4.
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search