Notice: This blog is no longer maintained. All new content is being published as guides/books/screencasts. Have a look around!

Should you test your ORM mappings?

September 25, 2014 - Andreas Eisele

Welcome back from the summer pause!

Inspired from a heated discussion at one of our clients and somewhat related to our last post about test transactionality is the consideration about whether one can and should test the basic object relational mapping at all.

So what is this about? Presume that you mapped your - entity to a database table using some common technologies in the Java world (JPA / Hibernate comes to mind). How do you know that this mapping is correct? How could you be confident that every property ends up going to and coming from the correct column? How would you even be confident that it uses the table you think it uses?

Obviously if we want to ensure that mapping correctness we have to invent some integration tests. So can we just fire up some test suite, create entities and then assert that we can read them from the database again? No that won't work. We are never making sure that the database picture get's asserted. We just assure that on the Java side of the mapping everything looks good.

So the actual idea is to go the database proper. This means inserting through your persistence layer and asserting on the JDBC level. It also means inserting on the JDBC level and asserting on the higher layer again. A neat little trick, isn't it? Not that much sadly. This is a lot of manual and duplicated work. Even when you take tools like DBUnit and Unitils into account, eventually you will end up defining and maintaining your complete ORM mapping a second time. The probability is high that your "manual test mapping" is a lot more complex in itself then what your persistence tooling provided. And then in the end when you labored a lot of effort into doing stuff twice or more who will tell you that your test mapping is correct? You could have done the same or even different errors again. Do we now need to test our tests and their tooling?

NO! It is our honest opinion that testing your ORM mapping is seldom worth the effort. Sure, if you have a complex usertype across 5 columns with some crazy conversions going on, do test it. But don't build an entirely new mapping test infrastructure to find out if your java attribute firstName gets mapped to firstName correctly - focus on providing some business value instead. ;)

And if you don't believe me, maybe Lukas Eder of Jooq fame could convince you otherwise.