Java Reference
In-Depth Information
JUnit best practices: explain the failure reason in assert calls
Whenever you use any of the JUnit assert* methods, make sure you use the sig-
nature that takes a String as the first parameter. This parameter lets you provide
a meaningful description that's displayed in the JUnit test runner if the assert fails.
Not using this parameter makes it difficult to understand the reason for a failure
when it happens.
F ACTORIZING SETUP LOGIC
Because both tests do the same type of setup, you can try moving that code into a
@Before annotated method. At the same time, you don't want to move it into a
new @Before method because you aren't sure which method will be executed first, and
you may get an exception. Instead, you can move it into the same @Before method.
As you add more test methods, you may need to adjust what you do in the @Before
methods. For now, eliminating duplicate code as soon as possible helps you write
more tests more quickly. Listing 3.8 shows the new and improved TestDefault-
Controller class (changes are shown in bold).
Listing 3.8 TestDefaultController after some refactoring
[...]
public class TestDefaultController
{
private DefaultController controller;
private Request request;
private RequestHandler handler;
@Before
public void initialize() throws Exception {
controller = new DefaultController();
request = new SampleRequest();
handler = new SampleHandler();
B
controller.addHandler(request, handler);
}
private class SampleRequest implements Request
{
// Same as in listing 3.1
}
private class SampleHandler implements RequestHandler
{
// Same as in listing 3.1
}
private class SampleResponse implements Response
{
// Same as in listing 3.1
}
@Test
public void testAddHandler()
{
C
 
 
 
Search WWH ::




Custom Search