简体   繁体   English

JMock无法模拟私有方法

[英]JMock unable to mock a private method

I am trying to write code to test a method by mocking the class in JMock, this method internally calls three different methods(one of them is a private method). 我正在尝试通过模拟JMock中的类来编写代码来测试方法,该方法内部调用了三个不同的方法(其中一个是私有方法)。 I set up the expectations for all the three internal methods. 我对这三种内部方法都设定了期望。 Then I call method, which is under test. 然后我调用正在测试的方法。 The test case fails saying that it expected the private method to be called and it was not called. 测试用例未能说它期望私有方法被调用而没有被调用。 What is happening is that the two internal methods(with default access specifier) are mocked successfully but the private method is not mocked and in fact the control reaches inside the actual private method causing the problem. 发生的情况是成功模拟了两个内部方法(具有默认的访问说明符),但未模拟私有方法,并且实际上控件进入了实际的私有方法内部,从而导致了问题。 When I change the access specifier of the private method to default access, then everything works fine, but I don't want to do that. 当我将私有方法的访问说明符更改为默认访问权限时,一切正常,但是我不想这样做。 Can somebody please explain this behavior and let me know how to resolve this problem 有人可以解释一下这种行为,让我知道如何解决此问题

JMock cannot mock private methods, plain and simple. JMock无法模拟简单而简单的私有方法。 Mockito cannot mock private methods either . Mockito也不能模拟私有方法 If you really want to mock private methods, you need to use the PowerMock framework. 如果您真的想模拟私有方法,则需要使用PowerMock框架。

You can use Jmockit also. 您也可以使用Jmockit。 It's an excellent library you can use for this use case. 这是一个很好的库,可用于此用例。 Keyword you can use: "Deencapsulation" . 您可以使用的关键字:“ Deencapsulation”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM