This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I've been searching google trying to find examples of using EasyMock to mock up JPA based DAO classes/interfaces. I've found a few things but they all connect to the database. I want to test my DAO's disconnected. I've tried mocking the EntityManagerFactory, JpaTemplate, etc, but there are so many abstractions I'm not able to get them all and I really am not even understanding what I am doing because I just started looking into EasyMock.
Gregg, What are you trying to test? Things like em.find() should be easy to mock because just the entity manager needs mocking. I guess I'm missing the point of the complexity. And a lot of JPA is configuration which doesn't seem to leave much to unit test.
Originally posted by Jeanne Boyarsky: Gregg, What are you trying to test? Things like em.find() should be easy to mock because just the entity manager needs mocking. I guess I'm missing the point of the complexity. And a lot of JPA is configuration which doesn't seem to leave much to unit test.
Well, that is probably part of my question. I'm not sure how extensive this testing needs to be. I mean, do I need to be testing CRUD methods for every single DAO? And should these tests be disconnected? I was reading Lasse's TDD book and he goes through testing JDBC based DAO's. He mocks the Datasource and the Connection.
In my JPA stuff there is an EntityManagerFactory and EntityManager. Then there is JpaTemplate which all my DAO's extend. JpaTemplate isn't an interface and when I try and mock it EasyMock complains about this.
The only method I would bother unit testing in there is the findAll because it has exception handling logic. (Which I hope is oversimplified here for the sake of example.)
The others are one liners where the test mirrors the implementation. I would integration test them all which provides the coverage. That said, they aren't any harder to test than findAll so there is no reason you couldn't.
I don't use Spring, but if I was testing this, I would create a superclass that extends JpaDaoSupport. Let's call it GreggsDaoSupport here. All my DAOs would extend that superclass. Then GreggsDaoSupport could have a method getJpaTemplateWrapper that does have an interface. Alternatively, you could use easyMock's cglib extension to mock out the concrete class. This is mainly a philosophical difference - either approach is find and would work.