[Updated] Using JUnits-@Rule for injecting EntityManagers during testing

Hi!

Today I would like to show you, how to use a JUnit-Rule for setting up and injecting a EntityManager during testing.

First we need at least JUnit version 4.10 and JEE6.

I will use EclipseLink as a persistence provider, but you can choose whatever your preferred persistence provider is.

The next step, after creating your project,  is to create a persistence.xml. Here we define a persistence unit named “RuleTutorialPU” which uses RESOURCE_LOCAL for transactionmode.

For this showcase I use Derby as a database, so I’ve ended with this configuration for the PU.

 

Now have we a working PU which targets to our testdatabase.

The next step is to create a JUnit-Rule which creates a EntityManager on our RuleTutorialPU and injects it to a given field in our test. For marking a field for injection I will reuse the existing @PersistenceContext annotation. This has multiple pros.

  • We must not introduce a new annotation,
  • we can use the attribute “unitName” for providing the required PU-name
  • we must not handle predefined field names or naming conventions like “PU_*” or something else (I hate when someone is doing this without a very good reason, and annotations frees us mostely from those decisions)
  • we must not provide an errorprone list of field names to the constructor (or somewhere else)
Let’s create our TestDBRule.

 

The method findFieldsRequestingEntityManager is simple usage of reflection were I implement some checks:

The main “magic” happens in createAndInjectEntityManagers

Finally I’ll show the SetupTestDBStatement. In this class, we start before executing the testcase transactions on the EntityManagers, executing the testcase and rollback the changes on the database. Start of transactions and rollback are surrounded by try-catch-blocks to ensure that the setup and tear down is done for every EntityManager.

I’ll upload a complete example to GITHUB this weekend.

Update

The example is located here

Outlook

With some little modifications it should also be possible to use setup / teardown implementation for the persistence units. I’m currently thinking about an extra annotation which points to a class which provides setup and tear methods via implementing one or two interfaces.

This way would provide maximal flexibility for choosing between a simple PU and a testclass specific setup / teardown, e.g. database structure, clean up etc. pp. .

Cheers

 
0 Kudos
Don't
move!

Leave a Reply

Your email address will not be published. Required fields are marked *