0

So I have used easymock for mocking my data layer objects while unit testing. I am using JPA for persistency. E.g. Project project = EasyMock.cre..(Project.class); etc.

Now the method which I want to test gets this project does some stuff and then persists it calling persist(project). project is a mocked object so it throws me error here. My manager is telling me since you just want to test the functionality of the method. The return value from db is not imp that is why you should use mocking instead of real db. So in case of this method which has persist method call, what should I do?

Thanks.

DataNucleus
  • 15,497
  • 3
  • 32
  • 37
Sara
  • 2,417
  • 7
  • 35
  • 52

1 Answers1

4

You should be mocking the entity manager rather than the entity.

The entity is just a pojo that you can easily create, you need to see if the persist is called on the entity manager.

Edit

That looks like you are creating an instance of the entity manager in the test under class through a static method. There is no easy way to mock it out.

You should pass the Entity manager to the object that uses it using dependency injection. Then instead of passing the real implementation, you can just pass the mock instance.

So your code would look something like:

Project project = ...    

EntityManager manager = EasyMock.createStrictMock(EntityManager.class); 
ClassUnderTest test = new ClassUnderTest(manager)

//You expect this to be called    
manager.persist(project);

EasyMock.replay(manager);

//The method you are testing
test.save(project);

EasyMock.verify(manager);

(I haven't used easymock for a while so the methods might not be quite right.)

plasma147
  • 2,191
  • 21
  • 35
  • Thanks, I think this is what I need. So for my entity manger I currently have something like this : EntityManager entityManager = Persistence.createEntityManagerFactory("AutomationCreatePU").createEntityManager(); Could you explain a little bit more how I can mock entity manager. Or any links for that? Thanks. – Sara Jul 16 '12 at 21:39
  • 1
    @Sara - Use the same method you're using to create the mock project and pass it into the class under test. – David Harkness Jul 16 '12 at 21:48
  • Thaks a bunch. I ll try that and get back to you. :) – Sara Jul 16 '12 at 22:03