Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EasyMock expecting private method calls

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

like image 841
KWJ2104 Avatar asked Aug 06 '12 18:08

KWJ2104


2 Answers

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.

like image 88
Vitaliy Avatar answered Oct 18 '22 06:10

Vitaliy


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.

like image 33
Makoto Avatar answered Oct 18 '22 08:10

Makoto