July 17, 2015

JUnit testing CDI and EJB with Mockito, OpenEJB and Arquillian


Unit testing EE have previously been hard, but since EE 6 and onward the EE specification has been improved on the test front.

Since EE 6 the following has been added:

  • javax.ejb.embeddable.EJBContainer – A standardized test container for EJB.
  • Portable JNDISyntax – Now all EE container must conform to the same JNDI registration and lookup name spaces. Before EE 6, there was no name standard and each EE container had each different name standard.

Do we need CDI and EJB injection for unit testing?

The general rule of thumb is to make unit tests fast, because if they are not, people will starts to disable test cases. And this will make unit tests contra productive.

Loading a CDI or EJB container takes time. Which is also true for Spring Application Context. So try to write your unit test without the need to load some kind of container.

JPA and JDBC can be tested with standard Java SE

See http://magnus-k-karlsson.blogspot.se/2015/02/hibernate-best-practise-jpa-20-and.html.

Logic and EJB can be tested with Mockito

When testing logic or EJB there is in most cases no need to create a EJB context. Try to use mockito, to mock your surroundings.

EJB Container Unit Testing

In some cases there is actually a need to create an EJB context. The two most common solutions are:

  • OpenEJB
  • Arquillian



  • Is faster to start and stop than Arquillian
  • More easier to learn
  • Easy to use maven dependency


  • Only support standard EE (which is also a pro, since then you know your code will run in any EE container.).
  • Does not support mere CDI, must use first an EJB to test pure CDI functionality. Can put EJB in test directory.




  • Can test EE container specific code.
  • Support test of pure CDI code.


  • Is slower than OpenEJB.
  • Its maven dependencies are long and complex.
  • Is harder to learn compared with OpenEJB.


No comments: