Embedding EJB 3.1 Container Into Your Unit Tests - Boot Time: 5 Seconds 📎
It simpler and faster, than you may think. The following no-interface view EJB 3.1:
@Stateless
public class HelloWorld {
public String hello(String message){
return "Echo: " + message;
}
}
...is tested with - the following unit test with embeddable EJB 3.1 container:
public class HelloWorldTest {
@Test
public void hello() throws NamingException{
EJBContainer ejbC = EJBContainer.createEJBContainer();
Context ctx = ejbC.getContext();
HelloWorld helloWorld = (HelloWorld) ctx.lookup("java:global/classes/HelloWorld");
assertNotNull(helloWorld);
String expected = "duke";
String hello = helloWorld.hello(expected);
assertNotNull(hello);
assertTrue(hello.endsWith(expected));
ejbC.close();
}
}
It was tested with Glassfish v3 b66 - it is important to use at least the build 66. The sample was developed with Netbeans 6.8 daily builds (should work with 6.7.1 as well).
There is absolutely no configuration or classpath changes needed. You will see an exception first - this issue is already reported. It doesn't, however, impact the test.
The entire test, with booting the container, takes on my machine about 5 seconds. The project [EmbeddableGlassfishEJB31Test] was already checked-in into: http://kenai.com/projects/javaee-patterns/.
[See BeanLocator, page 108 in "Real World Java EE Patterns Rethinking Best Practices" book for EJB 3.0 embeddable test practices, and page 111 for testing with transactions]