2011-10-23

JEE6: Integration testing with JBoss 7

Introduction

When your code utilises some of the JEE6 goodies, such as CDI or EJB, then it may become handy if not necessary to execute the tests for this code on the actual server as opposed to running it in a mocked unit test environment. Benefits?

Your tests run in the same environment (or similar) as your production code.

In certain cases, it actually makes testing possible, because even when using mocking certain JEE6 behaviours are hard to simulate in a unit test.

JBoss 5 was so slow... But with JBoss 7 it doesn't take so much time to start up the server. So tests can run as a part of your Maven build or inside your IDE.

As you can see, it does not do a lot - but it is an EJB and it uses @PersistenceContext. I did not expose any way to set the entityManager because I don't like having to change production code just so that tests can run. So, that would be rather hard to mock.
But we don't have to mock, we are going to run the test on the server.

Let's take a closer look.
First, the test is annotated with @RunWith(Arquillian.class). That is because we need Arquillian to orchestrate the entire test.
Arquillian will handle our @Deployment. This is where, using ShrinkWrap, we create the WAR file with our test and what we want to test with all its dependencies, also the external ones, from our pom.xml. This WAR file will be deployed to JBoss 7 when you run the test with Maven or from within your IDE.
I must admit that getting the dependencies right (i.e. giving it exactly what it needs and not too much) can be a bit tiresome and frustrating.

When the test is running, it's running on a remote instance of JBoss. That means you have to download JBoss 7 yourself. You can hardcode its location in this file, but it's not a good idea if you're sharing the project with other people. Instead, you can set your JBOSS_HOME system variable to something like e:\Servers\jboss-as-web-7.0.0.Final.

Download sample source code

As always, working code is available for you to download. Get it now from GitHub. There is a text file called SETUP that explains how to get it going (the database and so on).
If you have any questions, feel free to post them here and I will do my best to answer.