Embeded Glassfish for Integration Tests

Sun Glassfish server can be run in embeded mode, very useful for automated integration tests. Here’s how:

Maven Dependencies:

<dependency>
  <groupId>org.glassfish.distributions</groupId>
  <artifactId>web-all</artifactId>
  <version>10.0-build-20080430</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.glassfish.embedded</groupId>
  <artifactId>gf-embedded-api</artifactId>
  <version>1.0-alpha-4</version>
  <scope>test</scope>
</dependency>

If you are not using maven then add the above libs to you classpath. Getting the server started in simple

final URI APP_URI= UriBuilder.fromUri("http://localhost/").port(8888).path("myapp").build();
GlassFish server= new GlassFish(BASE_URI.getPort());
ScatteredWar war = new ScatteredWar(APP_URI.getRawPath(),
   new File("src/main/webapp"),
   new File("src/main/webapp/WEB-INF/web.xml"),
   Collections.singleton(new File("target/classes").toURI().toURL()));
server.deploy(war);

You can then use any HTTP Client to send a HTTP Request to the server on a defined port. For automated integration tests use TestNG “dependsOnMethods” feature to ensure that the server was started before executing you integration test group(s). You can then have anther test which depends on your integration test group(s) to ensure that the server is stopped when tests have finished.

You can stop the server with server.stop(). Note: If you are using Maven then using cargo to bring up the server may be more advisable.