我使用PowerMockito来模拟私有方法。但是被嘲笑却被称为。我需要测试strangeMethod(),它调用privateMethod()。
这是我的测试课程:
:v1
我的测试方法:
public class StringConvenience {
public static void main(String[] argv) {
String pattern = ".*Q[^u]\\d+\\..*";
String line = "Order QT300. Now!";
if (line.matches(pattern)) {
System.out.println(line + " matches \"" + pattern + "\"");
} else {
System.out.println("NO MATCH");
}
}
}
作为测试的结果,我得到了UnsupportedOperationException。这意味着,调用了privateMethod()。
答案 0 :(得分:2)
当您使用PowerMockito.spy(new ExampleService());
时,首先将所有方法调用委托给真实类的实例。你得到UnsupportedOperationException
的原因是什么?
PowerMockito.when(exampleService, "privateMethod").thenReturn("");
如果您想避免使用真实方法,请使用PowerMockito.mock( ExampleService.class);
和doCallRealMethod
/ thenCallRealMethod
作为不应被嘲笑的方法。
此示例显示私有方法被模拟:
类别:
public class ExampleService {
public String strangeMethod() {
return privateMethod();
}
private String privateMethod() {
return "b";
}
}
测试:
@PrepareForTest(ExampleService.class)
@RunWith(PowerMockRunner.class)
public class TestPrivate {
@Test
public void strangeMethodTest() throws Exception {
ExampleService exampleService = PowerMockito.spy(new ExampleService());
PowerMockito.when(exampleService, "privateMethod").thenReturn("a");
String actual = exampleService.strangeMethod();
assertEquals("a",actual);
}
}