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;

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

    public static void tearDownClass() throws Exception {

     * Test of findConfiguration method, of class ConfigurationService.
    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:

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   and   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!
Have fun!