Java 如何使用 PowerMockito 模拟私有静态方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25594090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I mock private static method with PowerMockito?
提问by Aaron
I'm trying to mock private static method anotherMethod()
. See code below
我正在尝试模拟私有静态方法anotherMethod()
。见下面的代码
public class Util {
public static String method(){
return anotherMethod();
}
private static String anotherMethod() {
throw new RuntimeException(); // logic was replaced with exception.
}
}
Here is me test code
这是我的测试代码
@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");
}
}
But every tile I run it I get this exception
但是我运行的每一个 tile 都会出现这个异常
java.lang.AssertionError: expected object to not be null
I suppose that I'm doing something wrong with mocking stuff. Any ideas how can I fix it?
我想我在嘲笑东西方面做错了什么。任何想法我该如何解决?
采纳答案by troig
To to this, you can use PowerMockito.spy(...)
and PowerMockito.doReturn(...)
.
为此,您可以使用PowerMockito.spy(...)
和PowerMockito.doReturn(...)
。
Moreover, you have to specify the PowerMock runner at your test class, and prepare the class for testing, as follows:
此外,您必须在您的测试类中指定 PowerMock 运行器,并准备类进行测试,如下所示:
@PrepareForTest(Util.class)
@RunWith(PowerMockRunner.class)
public class UtilTest {
@Test
public void testMethod() throws Exception {
PowerMockito.spy(Util.class);
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod");
String retrieved = Util.method();
Assert.assertNotNull(retrieved);
Assert.assertEquals(retrieved, "abc");
}
}
Hope it helps you.
希望对你有帮助。
回答by gigaSproule
I'm not sure what version of PowerMock you are using, but with the later version, you should be using @RunWith(PowerMockRunner.class)
@PrepareForTest(Util.class)
我不确定您使用的是哪个版本的 PowerMock,但是对于更高版本,您应该使用 @RunWith(PowerMockRunner.class)
@PrepareForTest(Util.class)
Saying this, I find using PowerMock to be really problematic and a sure sign of a poor design. If you have the time/opportunity to change the design, I would try and do that first.
说到这里,我发现使用 PowerMock 确实有问题,并且是设计不佳的明确标志。如果您有时间/机会更改设计,我会先尝试这样做。
回答by Umut Uzun
If anotherMethod() takes any argument as anotherMethod(parameter), the correct invocation of the method will be:
如果 anotherMethod() 接受任何参数作为 anotherMethod(parameter),则该方法的正确调用将是:
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);