In EJB 3.1, one can unit-test EJB using standadard EJB API, JUnit, and outside any application server. This is how I created an Eclipse java project to unit-test a simple EJB with GlassFish v3.
1. inside Eclipse, create a new java project, named
ejblite
.Build path:
$GLASSFISH_HOME/lib/embedded/glassfish-embedded-static-shell.jar $GLASSFISH_HOME/modules/javax.ejb.jar
Output dir: testApp (it is used in global jndi name in the test)
2. create a new java class named
TestBean
:package test;3. select
import javax.ejb.Stateless;
@Stateless
public class TestBean {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
}
TestBean.java
in the package panel, create a new JUnit Test Case (File -> New -> JUnit Test Case). Choose TestBean as the test target, and the test method for both business methods (add and multiply) will be generated, along with setUp and tearDown.4. modify the test case:
package test;5. select TestBeanTest class, and run it as JUnit test.
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import junit.framework.TestCase;
public class TestBeanTest extends TestCase {
private EJBContainer container;
private Context namingContext;
private TestBean testBean;
@Override
protected void setUp() throws Exception {
super.setUp();
container = EJBContainer.createEJBContainer();
namingContext = container.getContext();
testBean = (TestBean) namingContext.lookup("java:global/testApp/TestBean");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
namingContext.close();
container.close();
}
/**
* Test method for {@link test.TestBean#add(int, int)}.
*/
public final void testAdd() {
int a = 1, b = 2, expected = a + b;
assertEquals(expected, testBean.add(a, b));
}
/**
* Test method for {@link test.TestBean#multiply(int, int)}.
*/
public final void testMultiply() {
int a = 1, b = 2, expected = a * b;
assertEquals(expected, testBean.multiply(a, b));
}
}
Our EJB classes all reside under
testApp
directory (the output dir of the current project), and testApp
is also used as the module-name for the current EJB app. If you choose to use a different output dir value, you will also need to change the global jndi-name accordingly.If you are interested in using DataSource and JPA in EJB embeddable, check out EJB lite, JPA, DataSource embedded in java application.