Java Reference
In-Depth Information
public SampleRequest(String name)
{
this.name = name;
}
C
public SampleRequest()
{
this(DEFAULT_NAME);
}
public String getName()
{
return this.name;
}
}
[...]
@Test
public void testProcessRequestAnswersErrorResponse()
{
SampleRequest request = new SampleRequest(" testError ");
SampleExceptionHandler handler = new SampleExceptionHandler();
controller.addHandler(request, handler);
Response response = controller.processRequest(request);
D
E
assertNotNull("Must not return a null response", response);
assertEquals(ErrorResponse. class , response.getClass());
}
}
Introduce a member field to hold the request's name and set it to the previous ver-
sion's default B . Next, introduce a new constructor that lets you pass a name to the
request C , to override the default. At D you introduce an empty constructor, so exist-
ing calls will continue to work. Finally, call the new constructor instead E , so the
exceptional request object doesn't conflict with the fixture.
If you added another test method that also used the exception handler, you might
move its instantiation to the @Before fixture, to eliminate duplication.
JUnit best practices: let the test improve the code
Writing unit tests often helps you write better code. The reason is simple: a test
case is a user of your code. It's only when using code that you find its shortcom-
ings. Don't hesitate to listen to your tests and refactor your code so that it's easier
to use. The practice of test-driven development relies on this principle. By writing
the tests first, you develop your classes from the point of view of a user of your
code. See chapter 5 for more about TDD.
Because the duplication hasn't happened yet, let's resist the urge to anticipate
change and let the code stand (Extreme Programming's “No functionality is added
early” rule).
 
 
Search WWH ::




Custom Search