The Spring fallacy
Spring proponents will have you believe that "Unit Testing" of persistent classes is very hard without spring. This is not the case, and can be accomplished in only a few classes.
This is not spring-bashing - I'm sure that Spring is very useful for some. This is simply an alternative approach to one that was presented at InfoQ
To use these examples you will need the following libraries - all open source
- Using Oracle Jars http://www.oracle.com - then sign up
- J2EE Api - whereever you can get it.
We will be using a simple annotated class just to show the example.
The Persistent Stuff
This is where you might have used the ejbFindBy methods back in the day... its just an interface.. so you can conveniently have mocks and stubs for them.
And an implementation for the interface
Using an EntityManager. This means that we will create them in the transactional context in which they are used, rather than having them around for ever - as we might have used with an EntityManagerFactory. Short lived objects are very efficent these days.
If we are to have any hope of using the entity manager outside of a J2EE container, then we need to do so within a transaction. Managing this as part of a testcase is a bit hit-and-miss - better abstract it.
Creating a test Configuration
All systems have some way of getting their configuration. In real code the implementation here would be a little more intelligent.
Creating a test Entity Manager
This example uses Hibernate and Oracle, but you could do this with lots of other implementations. Note that the actual implementation doesn't escape - as far as the rest of the code is concerned, we are still only talking about EntityManagers.
To keep the amount of code in this page short - I used the autoDDL feature of hibernate. I would suggest never do this, and make sure to have a good database rebuilding script as part of the build process. Dropping and recreating databases takes only seconds.
We like to use the Builder pattern - it makes code much cleaner!
The actual persistence test
How it all looks
Here's a screenshot from IntelliJ after we have put all the code together.
Contact me - using the contact me page if you would like access to the svn repo. All the code is here though.
Nat & Nick