EasyMock expecting private method calls

强颜欢笑 提交于 2019-12-12 14:49:06

问题


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


回答1:


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.




回答2:


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.




回答3:


If you still want to use EasyMock, because changing it doesn't depend on you (work in an enterprise) you can use reflection to change the private field which your method returns, or any private field for that matter.

You can have these methods in a helper class for example. And use them as needed.



来源:https://stackoverflow.com/questions/11833945/easymock-expecting-private-method-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!