如何使用PowerMock模拟私有方法进行测试?
我有一个类,我想使用调用私有方法的公共方法来测试该类。我想假设私有方法工作正常。例如,我想要类似 doReturn....when...
的内容。我发现有使用PowerMock的可能解决方案,但这个解决方案对我不起作用。 怎样才能做到呢?有人遇到这个问题吗?
I have a class which I would like to test with a public method that calls private one. I'd like to assume that private method works correctly. For example, I'd like something like doReturn....when...
. I found that there is possible solution using PowerMock, but this solution doesn't work for me.
How It can be done? Did anybody have this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我不认为这里有问题。通过使用 Mockito API 的以下代码,我成功做到了这一点:
这是 JUnit 测试:
I don't see a problem here. With the following code using the Mockito API, I managed to do just that :
And here's the JUnit test :
适用于任何测试框架的通用解决方案(如果您的类不是
final
)是手动创建您自己的模拟。这不使用任何框架,因此它不那么优雅,但它总是可以工作:即使没有 PowerMock。或者,您可以使用 Mockito 执行步骤 2 和 3。如果您已经完成了步骤#1,则#3 适合您。
要直接模拟私有方法,您需要使用 PowerMock,如其他答案中所示。
A generic solution that will work with any testing framework (if your class is non-
final
) is to manually create your own mock.This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.
To mock a private method directly, you'll need to use PowerMock as shown in the other answer.
由于某种原因,布莱斯的回答对我不起作用。我能够对其进行一些操作以使其正常工作。这可能只是因为我有较新版本的 PowerMock。我用的是1.6.5。
测试类如下所示:
For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.
The test class looks as follows:
我知道一种方法,你可以调用你的私有函数来在mockito中进行测试
i know a way ny which you can call you private function to test in mockito
不带参数:
带
String
参数:With no argument:
With
String
argument:需要考虑的事情
确保私有函数正在调用另一个公共函数,并且您只能继续模拟公共函数。
Something to Consider
Make sure the private function is calling another public function and you can proceed only mocking the public function.