14 Juni 2010

EJB 3.1, JUnit and GlassFish Embedded incl. JPA and JDBC DataSource

Today I have my JUnit tests with GlassFish embedded up and running and like to share how to configure it.

First we have a look at how to run the tests with the EJBContainer from EJB 3.1:


public class ConfigurationServiceTest {


    private static EJBContainer container;
    private static ConfigurationService service;


    @BeforeClass
    public static void setUpClass() throws Exception {
        container = EJBContainer.createEJBContainer();
        service = (ConfigurationService) container.getContext().lookup("java:global/classes/ConfigurationService");
    }


    @AfterClass
    public static void tearDownClass() throws Exception {
        container.close();
    }


    /**
     * Test of findConfiguration method, of class ConfigurationService.
     */
    @Test
    public void testFindConfiguration() throws Exception {
        Configuration configuration = service.findConfiguration();
        System.out.println("From Configuration: " + configuration.getNextNewsletterSendDate());
    }
}

The most important line is the lookup of the EJB:
container.getContext().lookup(
  "java:global/classes/ConfigurationService");

Every found EJB is deployed to the embedded server and the JNDI name is built using java:global/classes and then the simple class name of the EJB.

That was all very straight forward. But then I had a problem configuring the JDBC datasource that the service needs using JPA. 
And again the solution was very simple. Just create the path org/glassfish/embed in classpath and add the domain.xml file from your "normal" GlassFish server. After copying you may want to do some cleanup with the file. You can delete everything that is under  <system-applications /> and  <applications /> because your application will run based on the classpath.

That's it.

When you want to us it with Maven2 simply put a new dependency in pom.xml.
Hint: In some situation it is best to have it as the first dependency!

<dependency>
  <groupId>org.glassfish.extras</groupId>
  <artifactId>glassfish-embedded-all</artifactId>
  <version>3.1-b04</version>
  <scope>test</scope>
</dependency>

Have fun!