Java Reference
In-Depth Information
JUnit best practices: one unit test equals one @Test method
Don't try to cram several tests into one method. The result will be more complex
test methods, which will become increasingly difficult to read and understand.
Worse, the more logic you write in your test methods, the more risk there is that
they won't work and will need debugging. This slippery slope can end with writing
tests to test your tests!
Unit tests give you confidence in a program by alerting you when something that
had worked now fails. If you put more than one unit test in a method, it becomes
more difficult to zoom in on exactly what went wrong. When tests share the same
method, a failing test may leave the fixture in an unpredictable state. Other tests
embedded in the method may not run or may not run properly. Your picture of the
test results will often be incomplete or even misleading.
Because all the test methods in a test class share the same fixture, and JUnit can
now generate an automatic test suite, it's just as easy to place each unit test in
its own method. If you need to use the same block of code in more than one test,
extract it into a utility method that each test method can call. Better yet, if all
methods can share the code, put it into the fixture.
Another common pitfall is to write test methods that don't contain any assert
statements. When you execute those tests, you see JUnit flag them as successful,
but this is an illusion of successful tests. Always use assert calls. The only time
when not using assert calls may be acceptable is when an exception is thrown to
indicate an error condition.
For best results, your test methods should be as concise and focused as your
domain methods.
Each test method must be as clear and focused as possible. This is why
JU
nit provides
you with the
@Before
,
@After
,
@BeforeClass
, and
@AfterClass
annotations: so you
can share fixtures between tests without combining test methods.
3.2.4
Improving testProcessRequest
When we wrote the
testProcessRequest
method in listing 3.7, we wanted to con-
firm that the response returned is the expected response. The implementation
confirms that the object returned is the object that we expected. But what we'd
like to know is whether the response returned equals the expected response. The
response could be a different class. What's important is whether the class identi-
fies itself as the correct response.
The
assertSame
method confirms that both references are to the same object.
The
assertEquals
method utilizes the
equals
method, inherited from the base
Object
class. To see if two different objects have the same identity, you need to pro-
vide your own definition of identity. For an object like a response, you can assign each
response its own command token (or name).