Unit testing the database layer

Testing the database layer. Usually an important part of many applications and thus everyone should test it.

But how do you do that?
(if you know how it’s done, this post is not for you, go read something more interesting then!)

You don’t want to setup an Oracle, MySQL, PostgreSQL and such just for running unit tests. Your option? Use an in memory database!

There are a couple of tools available on the opensource market to test your dao layer. I’ve put together an example for a database layer that is using Spring 3.1.2 with JPA2/Hibernate 4.x. For testing I choose the combination of Unitils, H2 in memory database and JUnit.

Unitils is the thing that creates the database using your entities or if you want it can also create your database using an sql script. I usually let hibernate create the database. And add some <dataset> xmls with data.

You can find the example code at github.

Take a look at the tests in src/test/java to see how it is done. There is one test that uses an xml file to populate the database and another test without an xml file. I’ve added Javadoc to the tests to explain what is happening.

This way of testing also allows you to test your service layer with a predefined dataset. Personally I prefer to mock stuff in the service layers. But for doing integration tests it can be useful to have an in memory database.

Happy Testing!

Applying different interceptors when using @Endpoint and PayloadRootAnnotationMethodEndpointMapping

Spring-WS

On the job we needed two webservice. Both in the same web context and servlet. We’re using the PayloadRootAnnotationMethodEndpointMapping which scans for  @Endpoint annotations to detect webservice endpoints.

We defined some interceptors for validation and security, the problem here was that only one of the two @Endpoint’s needed to be secured but with the annotation mapping it seems that all interceptors configured in the xml config file affect all @Endpoint.

After some googling and reading through the spring-ws reference I found that there currently is no solution or work around available. Which seems a bit dull. I did not want to create two servlet contexts I just wanted different interceptors for each @Endpoint annotated class.

Little thinking led me to the following solution: let’s extend PayloadRootAnnotationMethodEndpointMapping#createEndpointInvocationChain to add the needed interceptor to the invocation chain.

This resulted in an annotation to define interceptors defined in the application context
Continue reading “Applying different interceptors when using @Endpoint and PayloadRootAnnotationMethodEndpointMapping”