java EasyMock 期待私有方法调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11833945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EasyMock expecting private method calls
提问by KWJ2104
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
并且这两种方法都在同一个类中。parseFoo2 只是一个帮助 parseFoo 完成一些事情的辅助方法。我正在尝试测试 parseFoo 方法。EasyMock 中有没有人可以在 parseFoo2 的私有方法调用上指定返回值,就像我可以为对象指定实例方法调用的方式一样
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
谢谢
回答by Vitaliy
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 privatemethod 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!
为什么?因为这会使您的单元测试非常脆弱。考虑这样一种情况:您在一周内回到这段代码并决定您实际上并不需要 parseFoo2 方法,而您实际上想要内联其代码。或者您想将此方法拆分为两个或更多个较小的方法。所有非常有效的重构实践——但它们会破坏单元测试!
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.
每次进行这样的简单重构时,您都不想追逐单元测试。因此,模拟私有方法被认为是不好的做法。
回答by Makoto
If you find that you mustmock out a private method, then you can use PowerMock.expectPrivate()
. EasyMock is not capable of mocking private methods.
如果您发现必须模拟私有方法,则可以使用PowerMock.expectPrivate()
. EasyMock 不能模拟私有方法。
回答by dalvarezmartinez1
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.
如果您仍然想使用 EasyMock,因为更改它并不取决于您(在企业中工作),您可以使用反射来更改您的方法返回的私有字段,或任何与此相关的私有字段。
You can have these methods in a helper class for example. And use them as needed.
例如,您可以在助手类中使用这些方法。并根据需要使用它们。