JPA Implementation Patterns: Testing
Join the DZone community and get the full member experience.Join For Free
this week i will discuss various approaches to testing jpa code. the first question to ask is: what code do we want to test? two kinds of objects are involved when we talk about jpa: domain objects and data access objects (dao's) . in theory your domain objects are not tied to jpa (they're pojo's, right?), so you can test their functionality without a jpa provider. nothing interesting to discuss about that here. but in practice your domain objects will at least be annotated with jpa annotations and might also include some code to manage bidirectional associations ( lazily ), primary keys , or serialized objects . now things are becoming more interesting...
(even though such jpa specific code violates the pojo-ness of the domain objects, it needs to be there to make the domain objects always function the same way. whether inside or outside of a jpa container. the managing of bidirectional associations and using uuids as primary keys are nice examples of this. in any case, this is code you most certainly need to test.)
of course, we'd also need to test the dao's, right? an interesting question pops up here: why do we want to test the dao's? most of them just delegate to the jpa provider and testing the jpa provider makes no sense unless we are writing "learning tests" (see also robert martin's clean code ) or developing our own jpa provider. but the combination of the dao's and the jpa specific part of the domain objects is testworthy.
what to test against?
now that we know what to test, we can decide what to test against . since we are testing database code, we want our test fixture to include a database. that database can be an embedded in-memory database such as hsqldb (in memory-only mode) or a "real" database such as mysql or oracle. using an embedded database has the big advantage of being easy to set up; there is no need for everyone running the tests to have a running mysql or oracle instance. but if your production code runs against another database, you might not catch all database issues this way. so an integration test against a real database is also needed, but more on that later.
for most tests we need more than just the database. we need to set it up correctly before a test and after the test we need leave it in a usable state for the next test to run. setting up the schema and filling the database with the right data before running the test are not that hard to do (a.k.a. left as an exercise for the reader ), but returning the database to a usable state after the test is a more difficult problem. i've found a number of approaches to this problem:
the spring framework includes the
a test framework that uses transactions
to manage the state of your test fixture. if you annotate your test to be
will start a transaction before each test starts and roll back that
transaction at the end of the test to return to a known state. if you
are still using junit 3.8 you can extend the
base class for the same effect. this might seem nice but in practice
i've found this method to be unsatisfactory for a number of reasons:
- by default the jpa context is not flushed until the transaction is committed or a query is executed . so unless your test includes a query, any modifications are not actually propagated to the database which can hide problems with invalid mappings and such. you could try and explicitly invoke entitymanager.flush before the end of the test, but then the tests don't represent real scenario's anymore.
- also, saving an entity and then retrieving it in the same session does not uncover those nasty lazy loading issues. you're probably not even hitting the database as the jpa provider will return a reference to the object that you just saved!
- finally, in a test you might like to first store some data in the database, then run the tests, and finally check that the right data was written out to the database. to test this properly you need three separate transactions without the first two transactions being rolled back.
- if you use an embedded in-memory database that database will be clean when you run the first test and you won't need to worry about leaving it in a good state after all the tests are run. this means you will not have to roll back any transactions and can have multiple transactions within one test. but you might have to do something special between each test. for example, when using the spring testcontext framework you can use the @dirtiescontext annotation to reinitialize the in-memory database between tests.
- if you cannot use an in-memory database or re-initializing it after every test is too expensive, you can try and clear all the tables after every test (or before every test). for example, dbunit can be used to delete all data from your test tables or truncate all test tables . foreign key contraints may get in the way though, so you will want to temporarily disable referential integrity before performing these operations.
at what scope to test?
the next thing is to decide on the scope of the tests. will you write small unit tests, larger component tests, or full-scale integration tests? because of the way jpa works (the leakiness of its abstraction if you will), some problems might only surface in a larger context. while testing the persist method on dao in isolation is useful if you want to know whether the basics are correct, you will need to test in a larger scope to shake out those lazy loading or transaction handling bugs. to really test your system you will need to combine small unit tests with larger component tests where you wire your service facades with the daos under test. you can use an in-memory databases for both tests. and to complete your test coverage you will need an integration test with the database to be used in production using a tool such a fitnesse . because we are not specifically testing the jpa code in that case, having unit tests on a smaller scale will help you pinpoint dao bugs more quickly.
what to assert?
one final thing to tackle is what to assert in the tests. it might be that your domain objects are mapped to an existing schema in which case you want to make sure that the mapping is correct. in this case you would like to use raw jdbc access to the underlying database to assert that the right modifications were made to the right tables. but if the schema is automatically generated from the jpa mapping you probably will not care about the actual schema. you'll want to assert that persisted objects can be correctly retrieved in a new session. direct access to the underlying schema with jdbc is not necessary and would only make such test code brittle.
i'm pretty sure that i have not covered all test scenarios in this blog because testing database code is a very complicated area. i would love to hear how you test your database code, whether it uses jpa or some other persistency mechanism.
Opinions expressed by DZone contributors are their own.