Friday, February 14, 2014

Use OpenEJB for Junit Test

I was struggling yesterday to find a way to do Junit test for EJB and I found OpenEJB. But  the configuration gave me errors. So I thought to write a complete example because I couldn't find it anywhere.

First lets create a simple ejb.
Here is the interface

  package com.imesh.testejb;
  import javax.ejb.Local;
  public interface IHello {
    public string sayHi();
OK now the bean class.
  package com.imesh.testejb;
  import javax.ejb.Stateless;
   * Session Bean implementation class Hello
  public class HelloBean implements IHello{
     * Default constructor.
    public HelloBean() {
    public string sayHi() {
      return "HI";

Write our unit test class.

package com.imesh.test.ejbtest;
import static org.junit.Assert.*;
import java.util.Properties;
import javax.ejb.EJB;
import javax.naming.InitialContext;
import org.apache.openejb.api.LocalClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HelloBeanTest {
 public void setUp() throws Exception {
     Properties properties = new Properties();
     properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
     properties.setProperty("openejb.deployments.classpath.include", ".*");
     initialContext = new InitialContext(properties);
 public void tearDown() throws Exception {
 public void testSayHi() {
   bean = (IHello) initialContext.lookup("HelloBeanLocal");
   assertEquals("Hi", bean.sayHi());
  private InitialContext initialContext;
 private IHello bean ;

Ok now we need ejb-jar.xml file which should be located in the META-INF folder.
ejb-jar.xml contains nothing but   just empty tag. I couldn't run the unit test without this xml but nobody mentioned about this xml in examples. The error I got is relate to the JNDI name not found.
If you do use annotation in your ejb class, ejb-jar.xml will overwrite your annotation. So you can add this xml to test > resources > META-INF folder because we need this only for unit test. 
Next is dependencies. You may not want slf4j dependency. But I had some errors without it.



 That's it. We are done. you can compile and run the unit test.

1 comment: