Lets say I have a method that looks like this:
public static String[] parseFoo(Foo anObject){
Foo anotherObject = parseFoo2(anObject);
...
}
private static Foo parseFoo2(Foo anObject){
...
}
and both methods are in the same class. parseFoo2 is just a helper method that helps parseFoo get some stuff done. I'm trying to test the method parseFoo. Is there anyone in EasyMock that I can specify a return value on that private method call for parseFoo2 like the way I can specify instance method calls for an object with
EasyMock.createMock(...);
anObject.expect(...).andReturn(...);
because I want to test the public method, but I don't want to have to go into the private method and test the implementation inside.
Thanks
Don't do it. One of the corner stones of a good unit test is that it should rely as little as possible on implementation details. Mocking out a private method is exactly that.
Why? Because that makes your unit tests very brittle. Consider the situation where you come back to this code in a week and decide that you don't really need the method parseFoo2 and you actually want to inline its code. Or that you want to split this method into two or more smaller methods. All very valid refactoring practices- but they will break the unit test!
You don't want to be chasing unit tests each time you make a simple refactoring like that. Hence, it is considered bad practice to mock private methods.
If you find that you must mock out a private method, then you can use PowerMock.expectPrivate()
. EasyMock is not capable of mocking private methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With