EJB 3 JUnit testing with OpenEJB 3.1.4
This is quick example of how to create JUnit test to test the EJB 3.0 session bean. The approach is new innovation using @LocalClient. This will create EJB client for Java SE. The interface of the calculator class is,
package com.ojitha.calculator; import javax.ejb.Local; @Local public interface CalculatorLocal { public int add(int a, int b); }
This is the implement of the Calculator
package com.ojitha.calculator; import javax.ejb.Stateless; /** * Session Bean implementation class Calculator */ @Stateless public class Calculator implements CalculatorLocal { /** * Default constructor. */ public Calculator() { } @Override public int add(int a, int b) { return a + b; } }
Let's look at the openEJB based JUnit test class
package com.ojitha.calculator; 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; @LocalClient public class CalculatorTest { @EJB CalculatorLocal calculator ; @Before public void setUp() throws Exception { Properties p = new Properties(); p.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory"); InitialContext initialContext = new InitialContext(p); initialContext.bind("inject", this); } @After public void tearDown() throws Exception { } @Test public void testAdd() { assertEquals(6, calculator.add(4, 2)); } }
here the output
Apache OpenEJB 3.1.4 build: 20101112-03:32 http://openejb.apache.org/ INFO - openejb.home = /home/ojitha/workspace/EJBExample1 INFO - openejb.base = /home/ojitha/workspace/EJBExample1 INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) INFO - Found EjbModule in classpath: /home/ojitha/workspace/EJBExample1/build/classes INFO - Beginning load: /home/ojitha/workspace/EJBExample1/build/classes INFO - Configuring enterprise application: classpath.ear INFO - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container) INFO - Auto-creating a container for bean Calculator: Container(type=STATELESS, id=Default Stateless Container) INFO - Enterprise application "classpath.ear" loaded. INFO - Assembling app: classpath.ear INFO - Jndi(name=CalculatorLocal) --> Ejb(deployment-id=Calculator) INFO - Created Ejb(deployment-id=Calculator, ejb-name=Calculator, container=Default Stateless Container) INFO - LocalClient(class=com.ojitha.calculator.CalculatorTest, module=classes) INFO - Deployed Application(path=classpath.ear)
Comments
Post a Comment
commented your blog