Java Reference
In-Depth Information
3.3.2
Testing for exceptions
During testing, you found that addHandler throws an undocumented Runtime-
Exception if you try to register a request with a duplicate name. (By undocumented , we
mean that it doesn't appear in the signature.) Looking at the code, you see that get-
Handler throws a RuntimeException if the request has not been registered.
Whether you should throw undocumented RuntimeException exceptions is a larger
design issue. (You can make that a to-do for later study.) For now, let's write some tests
that prove the methods will behave as designed.
Listing 3.14 shows two test methods that prove addHandler and getHandler will
throw runtime exceptions when expected.
Listing 3.14
Testing methods that throw an exception
public class TestDefaultController
{
[...]
@Test(expected=RuntimeException.class)
public void testGetHandlerNotDefined()
{
SampleRequest request = new SampleRequest("testNotDefined");
// The following line is supposed to throw a RuntimeException
controller.getHandler(request);
}
B
C
D
E
@Test(expected=RuntimeException.class)
public void testAddRequestDuplicateName()
{
SampleRequest request = new SampleRequest();
SampleHandler handler = new SampleHandler();
// The following line is supposed to throw a RuntimeException
controller.addHandler(request, handler);
}
}
Annotate your method with the @Test annotation to denote that it's a test method B .
Because we're going to test an exceptional condition and we expect that the test
method will produce an exception of some kind, we need also to specify what kind of
an exception we expect to be raised. We do this by specifying the expected parameter
of the @Test annotation. Give the test an obvious name C . Because this test repre-
sents an exceptional case, append NotDefined to the standard testGetHandler pre-
fix. Doing so keeps all the getHandler tests together and documents the purpose of
each derivation.
At D , you create the request object for the test, also giving it an obvious name.
Pass the (unregistered) request to the default getHandler method E . Because this
request has no handler attached, a RuntimeException should be raised.
F
 
 
 
 
Search WWH ::




Custom Search