views:

303

answers:

2

I've got a couple of questions concerning the integrated testing EJB 3.0 components using JUnit.

In your JUnit tests you can inject to session beans resource-local entity managers and therefore "simulate" ejb-container. But what if...

  1. What if you need to test if transaction attributes on your ejb methods are handled properly? Can this be done outside the container? If not, what is the simplest way to test it inside the container?

  2. What if you need to assure there are some test records in db before each test? How would you assure that after test execution (even if it fail) db is cleaned of test data?

A: 

If you happen to be using Maven or even if you're not, this might be helpful. The typical way to test transactional semantics is with an in-memory database like H2 or HSQLDB (Hypersonic). So in effect, you're testing inside a very lightweight container. Hibernate can be configured as your JPA implementation. It will persist the data to a fully-functional relational database running entirely in RAM.

As for fixtures, there are quite a few options, one of the more popular being DbUnit, but in my experience, they're more complicated than they're worth. I prefer to create my own "builder" classes that set up my tests with the necessary model objects. I like for the configuration "setters" to return an instance of the builder so that I can chain calls together like so:

  this.emf = Persistence.createEntityManagerFactory ("hibernate-hsqldb");
  Widget widget = new WidgetBuilder(this.emf).setAnOption(4).setAnother("test").build();

Typically, the emf will be created in the setUp method and closed in the tearDown. This completely initializes the database in between test runs.

jcrossley3
+2  A: 

You can also use embeddable JBoss to unit test EJBs, as discussed in #553031

Its not a pretty solution, but it works.

toolkit