Java Reference
In-Depth Information
The last issue to solve is the one involving the @Before and @After methods. The
solution shown in listing 6.3 isn't optimal because JU nit will start and stop the server
for every test method. Even though Jetty is fast, this process isn't necessary. A better
solution is to start the server only once for all the tests by using the JU nit annotations
we described in the second chapter of the topic: @BeforeClass and @AfterClass .
These annotations let you execute code before and after all @Test methods in a class.
Isolating each test versus performance considerations
In previous chapters, we went to great lengths to explain why each test should run
in a clean environment (even to the extent of using a new class loader instance).
But sometimes there are other considerations to take into account. Performance
is a typical one. In the case of Jetty, even if starting the server takes only 1 second,
once you have 300 tests, it will add an overhead of 300 seconds (5 minutes). Test
suites that take a long time to execute are a handicap; you'll be tempted not to
execute them often, which negates the regression feature of unit testing. You must
be aware of this tradeoff. Depending on the situation, you may choose to have lon-
ger-running tests that execute in a clean environment or instead tune the tests for
performance by reusing some parts of the environment. In the example at hand, you
use different handlers for different tests, and you can be fairly confident they won't
interfere with each other.
W RITING THE TEST CLASS
We can now easily write the test class using the @BeforeClass annotation, as demon-
strated in listing 6.5.
Listing 6.5
Putting it all together
[...]
import java.net.URL;
[...]
public class TestWebClient {
@BeforeClass
public static void setUp() throws Exception() {
Server server = new Server(8080);
TestWebClient t = new TestWebClient();
Context contentOkContext = new Context(server, "/testGetContentOk");
contentOkContext.setHandler(t. new TestGetContentOkHandler());
server.setStopAtShutDown( true );
server.start();
}
@Test
public void testGetContentOk() throws Exception {
WebClient client = new WebClient();
String result = client.getContent( new URL(
 
 
 
 
Search WWH ::




Custom Search