1- Add the Glassfish embedded EJB container dependency to your Maven POM file. Also the JUnit dependency.
2- The service class is annotated with @Stateless as bellow
3- Now the unit test class could be as bellow:
<dependency> <groupId>org.glassfish.main.extras</groupId> <artifactId>glassfish-embedded-all</artifactId> <version>3.1.2</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </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
package com.ithinkisink.blog.service; @Stateless 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; import com.ithinkisink.blog.service.MyService; /** * *@author Belal */ public class MyServiceTest { private static Context ctx; private static EJBContainer ejbContainer; private MyService myService; @BeforeClass public static void setUpBeforeClass() { ejbContainer = EJBContainer.createEJBContainer(); System.out.println("Container Opening" ); ctx = ejbContainer.getContext(); } @AfterClass public static void tearDownAfterClass() { ejbContainer.close(); System.out.println("Container Closing" ); } @Test 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!"); } }
No comments:
Post a Comment