lördag 12 januari 2013

ejb + jpa + test = true?

Just finished off my test boilerplate for my javaEE project. I used the openEJB embedded container to deploy my ejb. I also fixed to possibility to test entities via hibernate in the same testcase. I think that's pretty cool since you actually can do more integration close testing even before deploying to a real application server. Trying to adapt to Antionio Goncalves nomock movement.

So I just wanted to show off my simple boilerplate as well:
@LocalClient
public class EjbTestCase {

    public static EJBContainer container;
    public static Context context;
    private static Properties prop;

    @Resource
    protected UserTransaction userTransaction;

    @PersistenceContext
    protected EntityManager entityManager;

    @BeforeClass
    public static void setup() {
        prop = new Properties();
        prop.put("jdbc/testDB", "new://Resource?type=DataSource");
        prop.put("jdbc/testDB.JdbcDriver", "org.hsqldb.jdbcDriver");
        prop.put("jdbc/testDB.JdbcUrl", "jdbc:hsqldb:mem:example");
        prop.put(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.openejb.client.LocalInitialContextFactory");

        container = EJBContainer.createEJBContainer(prop);
        context = container.getContext();
    }

    @Before
    public void setupEm() throws NamingException, SystemException,
            NotSupportedException {
        context.bind("inject",this);
        userTransaction.begin();
    }

    @After
    public void tearDownEm() throws HeuristicRollbackException, 
            RollbackException, HeuristicMixedException, SystemException {
        userTransaction.rollback();
    }

    @AfterClass
    public static void tearDown() {
        container.close();
    }
}

Pretty neat huh? At least I like it and thats whats matters right now :). As you can see you are able to get the context from the container + a entityManager in the same test.

The code is on github: examplesJavaEE

Inga kommentarer:

Skicka en kommentar