As I continue my look at the new Core Rules implemented in JUnit 4.7 the next on my list was the ExternalResource Core Rule.
This rule is intended to be implemented for Servers, Sockets, Database connections etc. It serves as base class for rules like the TemporaryFolder rule I have previously blogged about. It serves as a pattern for such rules with the before and after methods that should be overriden to provide the necessary functionality.
My experimental test sets up the ExternalResource instance for a HttpServer in the before() method and removes it in the after() method. The test check that the server is initialized and set up as expected, whilst the @After test which runs after each test confirms that the server is removed once a test has completed.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import com.sun.net.httpserver.HttpServer;
public class JUnitCoreExternalResourceRuleTest {
private static HttpServer testServer;
// ExternalResource core rule allows the set up of an external resource
// before a test (a file, socket, server, database connection, etc.),
// and guarantee to tear it down afterward:
@Rule
public ExternalResource resource = new ExternalResource() {
@Override
protected void before() throws Throwable {
testServer = HttpServer.create(new InetSocketAddress("localhost", 9999),
0);
testServer.start();
}
@Override
protected void after() {
testServer.stop(0);
testServer = null;
}
};
@Test
public void testExternalResource() throws IOException {
assertNotNull(testServer);
assertNotNull(testServer.getAddress());
assertEquals(9999, testServer.getAddress().getPort());
}
@After
public void testServerNoLongerExists() {
assertNull(testServer);
}
}
The difference between using the ExternalResource Core Rule and putting the code in the @Before and @After method is that this interceptor occurs after the @Before and before @Test (before() method) and after the @Test and before @After (after() method). Additional information could be put in the @Before and @After methods as a result.
