【发布时间】:2016-02-29 13:57:58
【问题描述】:
我正在使用 PowerMockito 来模拟私有方法。但相反被嘲笑它被称为。我需要测试调用privateMethod()的strangeMethod()。
这是我的测试类:
public class ExampleService {
public String strangeMethod() {
privateMethod();
return "Done!";
}
private String privateMethod() {
throw new UnsupportedOperationException();
}
}
我的测试方法:
@Test
public void strangeMethodTest() throws Exception {
ExampleService exampleService = PowerMockito.spy(new ExampleService());
PowerMockito.when(exampleService, "privateMethod").thenReturn("");
exampleService.strangeMethod();
}
作为测试的结果,我得到了 UnsupportedOperationException。这意味着,privateMethod() 被调用。
【问题讨论】:
-
你确定你首先需要这个吗?这看起来很脏,一个方法是私有的是有原因的。
-
尝试使用
@PrepareForTest({ExampleService .class})和@RunWith(PowerMockRunner.class)注释您的测试类
标签: java unit-testing junit mockito powermock