0

I am testing a class let say MyClass with JUnit. I am using easymock to isolate the need for db. It works fine. So if there is a call to a model object I just mock that object. E.g. if I have

public void method(Project project) { project.getName(); ..}

inside MyClass I just use mockedProject. Then I say MyClass.method(mockedProject); But what if I have this.getName() inside MyClass. In that case, since I want the real object for the class which I am testing (MyClass) I cannot mock MyClass object. So I cannot define a return value for MyClass object as it is a real object. Please have in mind that getName() would go throw the db which I don't want it to go.

What should I do in this case when I have this.method() and where the method works with db. I cannot mock this object which I am testing. Thanks.

Sara
  • 2,417
  • 7
  • 35
  • 52

2 Answers2

1

If you are able to mock the classes that you use to access the DB then do that and then this.getName() will use the mocked classes and will get whatever data you defined.

If the DB access classes cannot be mocked, then you can't really do anything.

UPDATE:

Testing JPA entities might be a bit trickier, if you can mock the actual entity then by all means, go for it and have it return whatever you like instead of the DB result. But I'm not sure it is possible.

I suggest you take a look here and here for a more elaborate example.

Tomer
  • 17,787
  • 15
  • 78
  • 137
  • I am using JPA and I have entity classes. By mocking classes do you mean mocking entity classes which have the getter and setter to db columns? Also this is the class which is not intended to access db explicitly rather throw call to entity classes. But here at this getName() method I have written a query to db. And "This" is the class which I want to test its functionality so should I still mock it? – Sara Jul 16 '12 at 15:07
  • Hmmss what do you mean? I am just having entity classes+xml files for ORM. I am not using entity manger. – Sara Jul 16 '12 at 15:22
  • 1
    Are you using a framework like Hibernate? Or straight up JPA? – Tomer Jul 16 '12 at 15:24
  • Yes I am using Hibernate. At the getName() method I have a Hibernate criteria. – Sara Jul 16 '12 at 15:26
0

you should mock the classes which access the DB within MyClass.getName() (e.g. EntityManager) and record the desired behavior for these mocks also

Korgen
  • 5,191
  • 1
  • 29
  • 43