[英]Powermock verify private static method call in non static method
Dear stackoverflow comrades, I again have a problem in getting a specific PowerMock / Mockito case to work. 亲爱的stackoverflow同志,我再次遇到一个问题,让特定的PowerMock / Mockito案例工作。 The issue is, that I need to verify the call of a private static method, which is called from a public non-static method .
问题是,我需要验证私有静态方法的调用,该方法是从公共非静态方法调用的 。 A similar example I posted previously on How to suppress and verify private static method calls?
我之前发布的一个类似的例子如何抑制和验证私有静态方法调用?
This is my code: 这是我的代码:
class Factory {
public String factorObject() throws Exception {
String s = "Hello Mary Lou";
checkString(s);
return s;
}
private static void checkString(String s) throws Exception {
throw new Exception();
}
}
And this is my testclass: 这是我的测试类:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {
public void testFactory() throws Exception {
Factory factory = mock(Factory.class);
suppress(method(Factory.class, "checkString", String.class));
String s = factory.factorObject();
verifyPrivate(factory, times(8000)).invoke("checkString", anyString());
}
}
The problem here is, that the Test is successful, but it shouldn't be. 这里的问题是,测试是成功的,但不应该。 It shouldn't be because the private static method should be called exactly 1 times.
它不应该是因为私有静态方法应该被正确调用1次。 But no matter what value I put in times(), it always verifies it as true... halp :(
但无论我在时间()中放置什么价值,它总是验证它是真的...... halp :(
Ok, I think I found the answer, but it was a headache. 好吧,我想我找到了答案,但这很头疼。 Rudy gave me the final hint with using using a spy, but it was still not trivial (although the solution looks "baby-easy").
Rudy在使用间谍时给了我最后的暗示,但它仍然不是微不足道的(尽管解决方案看起来很“容易”)。 Here is the complete solution:
这是完整的解决方案:
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.spy;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {
public void testFactory() throws Exception {
Factory factorySpy = spy(new Factory());
String s = factorySpy.factorObject();
doNothing().when(factorySpy, "checkString", anyString());
verifyPrivate(factorySpy, times(1)).invoke("checkString", anyString());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.