If you're using JPA, you don't need to mock your Project objects, because they are probably just dumb POJO's, right? What you need to mock is just the persistence manager object (EntityManager). In the simplest case (if you're using Mockito or Easymock with 'niceMock') you may just need to create the mock and inject it and that's it. Depending on what you're testing, you will probably want to do more than that: verifying that a save
or merge
method is called, specifying that it is to return a particular Project object on a get
call, etc.
Mocking the EntityManager has several benefits:
- It runs very fast - much faster than even an embedded database. These tests are going to be run many many times, so it's important that they not be too much of a burden.
- You don't need to populate a real database. Although you might need to do that anyway for some integration tests, it's hard to come up with a database that covers all of the scenarios that you want. With mocking, you can create the specific scenario you want right in the test itself.
- You may want to test certain conditions that would be very difficult to make happen in reality, such as IO errors or data that already exists in the database but that violates some constraints. With mocking, you just tell the mock to throw an exception when the method is called. Connecting to a real database (even embedded) it would be very difficult (if not impossible) to make it happen.
Mocking a POJO has none of these benefits. It's just as fast to execute the code of a POJO as a mocked POJO. Populating a POJO can be a bit of a pain, but not as much as setting up the behavior of a mocked POJO. And since POJO's don't (normally) have much in the way of external dependencies, the third benefit is rarely required.