2

I want to write integration tests for an ejb that does some basic CRUD operations.
here is how my test looks like now:

@Test
public void testAdd() {
    EJBContainer container = javax.ejb.embeddable.EJBContainer.createEJBContainer();
    MyEJBLocal myEjb= (MyEJBLocal)container.getContext().lookup("java:global/classes/MyEJB");

    // assuming I empty the database in the setup
    myEjb.add();
    int numOfEntities= myEjb.getAll().size();
    Assert.assertTrue("Unexpected number of entities", (numOfEntities==1));
    container.close();
}

obviously, this is not a good test but how to properly integrate DBUnit or any similar framework to control the state of the database before and after the add() method?

Iam using EJB, Hibernate and embedded Glassfish

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
Ahmad Abdelghany
  • 11,983
  • 5
  • 41
  • 36

2 Answers2

4

You need to use Arquillian to properly test your EJBs. Arquillian allows you to run integration tests which complement regular mocked-services unit tests.

I would advice you having two separate profiles:

  • one for using an in-memory db (HSQLDB, H2) running fast and validating JPQL/Criteria queries

  • another one connecting to a DB server clone you are using in your production environment.

    This second approach is useful for testing database specific features you might use (window functions, common table expressions, native queries) and also transaction logic (dead-locks, optimistic locking failures)

Community
  • 1
  • 1
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • thanks, this blog is very useful yet I still wonder if it is possible to integrate DBUnit (using datasets) without the use of Arquillian? – Ahmad Abdelghany Dec 18 '14 at 00:49
  • @AhmadAbdelghany **yes** it is possible. But then it will be about unit testing not integration testing. You can use [spring-dbunit](https://github.com/excilys/spring-dbunit) which gives you a convenient `@DataSet` annotation or you can write your own annotation that does the same. **But personally**: I found writing and maintaining of many DbUnit xml datasets time-consuming and error prone - so I switched to a [DbSetup](http://dbsetup.ninja-squad.com/). – G. Demecki Dec 18 '14 at 07:14
1

I advise you against using an embedded Glassfish. Why? Because of this.

As @VladMihalcea already said: Arquillian may be the best option for you. To control a DB state you basically have at least two options:

Personally I would recommend DbSetup for database population and Fest or Hamcrest for BDD-style assertions.

halfer
  • 19,824
  • 17
  • 99
  • 186
G. Demecki
  • 10,145
  • 3
  • 58
  • 58