Tag Archives: javaee

How to unit test EJB3 without a container

Unit test EJB3 without a container has become much easier since the EJB 3.1 spec with the introduction of the embeddable EJBContainer concept. An embeddable EJBContainer is a container for enterprise beans that does not require a Java EE server to run.

Interesting usage scenarios are:

  • EJB unit testing: you don’t need to install a JavaEE server for EJB development, unit testing and deployment to the container
  • Lightweight: the embeddable container has a much smaller footprint
  • Fast: starts faster than the full server, because it only initializes EJB-related components

Sample code

Below you can find a simple setup method for a JUnit test that configures the Embeddable EJBContainer.

@Before
public void setup() {
	Properties properties = new Properties();
	properties.setProperty(EJBContainer.MODULES, "myModule");
	properties.put(EJBContainer.PROVIDER, "tomee-embedded");
	Context context = EJBContainer.createEJBContainer().getContext();
}

@After
public void tearDown() throws NamingException {
	ejbContainer.close();
}

Here myModule is the module-name defined in ejb-jar.xml file

So how does the EJBContainer start an embedded EJB container? You’ll need to provide an embedded EJB container on the classpath. Normally all Application servers supporting JavaEE6 have to provide such an embedded EJB container.

Apache TomEE container This example uses Apache TomEE as it provides an easy way to specify the correct dependencies via Maven.

<dependency>
	<groupId>org.apache.openejb</groupId>
	<artifactId>tomee-embedded</artifactId>
	<version>1.5.2</version>
</dependency>            
<dependency>
	<groupId>javax</groupId>
	<artifactId>javaee-api</artifactId>
	<version>6.0</version>
	<scope>provided</scope>
</dependency>

The properties.put(EJBContainer.PROVIDER, “tomee-embedded”) makes sure that we will use Apache TomEE when running the test. (even if there is another provider on the classpath)