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.
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.