Embedding Glassfish V3 in Unit Test - Two Jars, Three Lines Of Code And Five Seconds Start With Deployment 📎
There is already a great blog entry about using Glassfish v3 in embedded mode (I "reused" some ideaas and even code from the post - this is how web works :-)). It explains the whole process, to install, build and test Glassfish v3 using maven 2. However I just liked to do it without maven - and as easy as possible. To start glassfish you only need two jar:
- gf-embedded-api-1.0-alpha-4.jar
- web-all-10.0-build-20080430.jar
Having them in the classpath, you can start glassfish v3 just from your code - in process:
GlassFish glassfish = new GlassFish(port);
It is not only possible to start glassfish in embedded code, it is even possible to deploy applications on the fly. The following code does exactly that:
ScatteredWar war = new
ScatteredWar(NAME, new File("src/main/resources"), new
File("src/main/resources/WEB-INF/web.xml"), Collections.singleton(new
File("build/classes").toURI().toURL()));
glassfish.deploy(war);
...and the full test code:
import org.glassfish.embed.GlassFish;
import org.glassfish.embed.ScatteredWar;
//and other obvious imports
public class HelloServletTest{
private final String NAME = "AppTest";
public static int port = 9999;
private GlassFish glassFish;
@Before
public void bootGlassfish() throws Exception{
this.glassFish = newGlassFish(port);
assertNotNull(this.glassFish);
}
@Test
public void testServlet() throws Exception {
URL url = new URL("http://localhost:" + port + "/" + NAME + "/HelloServlet");
BufferedReader br = new BufferedReader(
new InputStreamReader(
url.openConnection().getInputStream()));
assertEquals("Hallo from servlet", br.readLine());
}
private GlassFish newGlassFish(int port) throws Exception {
GlassFish glassfish = new GlassFish(port);
ScatteredWar war = new ScatteredWar(NAME,
new File("src/main/resources"),
new File("src/main/resources/WEB-INF/web.xml"),
Collections.singleton(new File("build/classes").toURI().toURL()));
glassfish.deploy(war);
System.out.println("Ready ...");
return glassfish;
}
@After
public void shutdown(){
this.glassFish.stop();
}
The unit test is only a sample, in general I woul start glassfish in the static @BeforeClass method - for one test it is good enough.
Glassfish v3 is not production ready yet - but it becomes more and more interesting for development. Cannot wait for embeddable EJB 3 containers :-).
I checked in the whole project (with servlet, glassfish jars and the unit test) into the p4j5. The project name is: EmbeddedGlassfishWeb. The remaining question is: from where I have this two jars - the answer is simple: from the maven repository :-).
So, and I'm going to present this stuff now - I'm at Jazoon :-).