adam bien's blog

How To Unit-Test EJB 3 ...in 0.8 Seconds [source code included] 📎

EJB 3 are just annotated classes - so it is straight forward to unit-test them. However, you will have to "emulate" the Dependency Injection and boot the EntityManager by yourself. It will cost you few additional lines of code. EJB 3.1 will solve the problem entirely - with an embeddable container.  Meanwhile you can use openEJB for boot the entire container within Unit-Test:


public class HelloBeanTest {
    private Hello hello;

    @Before
    public void bootContainer() throws Exception{
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
        Context context = new InitialContext(props);
        hello = (Hello) context.lookup("HelloBeanLocal");

    }

openEJB provide an own JNDI-SPI implementation, and plugs so naturally as JNDI-provider. Only one line (the bold one) makes your dependent on openEJB. You could even factor out the settings into jndi.properties. You will get from the lookup a fully-featured EJB 3 with injected dependencies and persistence (additional, but still lean, configuration is required here)


    @Test
    public void hello(){
        assertNotNull(hello);
        String message = "hugo";
        String echo = hello.hello(message);
        assertNotNull(echo);
        assertEquals(message,echo);
    }

The EJB is just an usual one:


public interface Hello {
    public String hello(String message);
}

@Stateless
@Local(Hello.class)
public class HelloBean implements Hello{

    public String hello(String message){
        return message;
    }
}

The whole source, project and needed libraries are pushed into: http://kenai.com/projects/javaee-patterns/. openEJB is lean - the only problem is the amount of libraries needed to run the test. I would prefer a single JAR. Maven, however, solves the problem for you in general.

Btw. I would really like to test Glassfish v3 Embeddable Container - should be available soon...

[This sample is not in my book :-)]