如何使用PowerMockito模拟私有静态方法?
2022-09-01 18:36:13
我试图嘲笑私有静态方法。请参阅下面的代码anotherMethod()
public class Util {
public static String method(){
return anotherMethod();
}
private static String anotherMethod() {
throw new RuntimeException(); // logic was replaced with exception.
}
}
这是我的测试代码
@PrepareForTest(Util.class)
public class UtilTest extends PowerMockTestCase {
@Test
public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc");
String retrieved = Util.method();
assertNotNull(retrieved);
assertEquals(retrieved, "abc");
}
}
但是我运行它的每个磁贴我都会得到这个异常
java.lang.AssertionError: expected object to not be null
我想我在嘲笑东西方面做错了什么。任何想法我该如何解决它?