Java Reference
In-Depth Information
the expected result. Now we want to look at another aspect of testing our applica-
tion: scalability. How scalable is our DefaultController class?
We're going to write some tests and expect that they run below a given time bar-
rier. To do this, JU nit provides us with another parameter to the @Test annotation
called timeout . In this parameter, you can specify your time barrier in terms of milli-
seconds, and if the test takes more time to execute, JU nit will mark the test as failed.
For example, let's look at the code in listing 3.15.
Listing 3.15
Timeout tests
[...]
public class TestDefaultController
{
[...]
@Test(timeout=130)
public void testProcessMultipleRequestsTimeout()
{
Request request;
Response response = new SampleResponse();
RequestHandler handler = new SampleHandler();
B
C
for ( int i=0; i< 99999; i++)
{
request = new SampleRequest(String.valueOf(i));
controller.addHandler(request, handler);
response = controller.processRequest();
assertNotNull(response);
assertNotSame(ErrorResponse.class, response.getClass());
}
}
We start by specifying the timeout parameter in milliseconds, which we expect to be
our time barrier B . Then C we declare the Request , Response , and RequestHandler
objects we're going to use in the test. At D we start a for loop to create 99,999 Sample-
Request objects and add them along with a handler to the controller. After that, we
invoke the processRequest() method of the controller and assert E that we get a non-
null Response object and also that the Response we get isn't an ErrorResponse .
You might consider the 130 milliseconds time barrier to be optimistic, and you're
right. This time barrier was the lowest possible on my machine. But the execution
time depends on the hardware it runs on (processor speed, memory available, and so
on) and also on the software it runs on (mainly the operating system, but also the Java
version, and so on). For different developers this test would fail or pass. Further, when
adding more functionality in the processRequest() method, the time barrier we've
chosen will become insufficient for our needs.
We get to the point where a few timeout tests might fail the whole build for some
developers. Sometimes it's good to skip some of the tests. In JU nit 3.x we had to
change the name of the test method (to not start with the test prefix). In version
4.x of JU nit, however, we have a nice way to skip a test. The only thing we need to do
D
E
 
 
 
Search WWH ::




Custom Search