Friday, December 16, 2011

Test: Unit test EJB 3 in 8 seconds on Apache OpenEJB

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;
    }
}
You would really like to test it on Glassfish v3 Embeddable Container.

No comments :

Post a Comment