Using JUnit with GlassFish EJB embedded EJB container

1- Add the Glassfish embedded EJB container dependency to your Maven POM file. Also the JUnit dependency.

The scope is test so it can be applied during the testing of the application.

2- The service class is annotated with @Stateless as bellow
public class MyService {
   public String getMessage() {
      return "Hello!";
For the sake of simplicity, the service class doesn't implement an interface as EJB supports injecting classes with no need to have interfaces.

3- Now the unit test class could be as bellow:
import javax.ejb.embeddable.EJBContainer;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import javax.naming.NamingException;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;


 *@author Belal
public class MyServiceTest {

   private static Context  ctx;
   private static EJBContainer ejbContainer;
   private MyService myService;

   public static void setUpBeforeClass() {
      ejbContainer = EJBContainer.createEJBContainer();
      System.out.println("Container Opening" );
      ctx = ejbContainer.getContext();

   public static void tearDownAfterClass() {
      System.out.println("Container Closing" );

   public void getMessageTest() throws NamingException {
      //note the JNDI path of the EJB container in case you used another container, this would need to be changed!
      myService = (MyService) ctx.lookup("java:global/ejb-app/classesejb/MyService");
      Assert.assertEquals(myService.getMessage(), "Hello!");


Popular posts from this blog

JavaOne 2015 Session: EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples by Gohar

Spring Core - Different Types of Bean Injection

PrimeFaces Push with Atmosphere