java 如何在 powermock 中模拟 void 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25132547/
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 to mock a void method in powermock
提问by user2831237
How to mock a void method which is non-static, non-finalThe signature of method is as below. I'm using Powermockito.
如何模拟一个非静态、非 final 的 void 方法方法的签名如下。我正在使用 Powermockito。
public class Name{
public void methodName{
...
...
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({Name.class})
public class TestClass{
@Test
public void testMethodName(){
PowerMockito.doNothing().when(Name.class, methodName);
//some when calls after this and assert later on
}
I want to DO Nothing when methodName is called. the above code is not working. it says methodName cannot be resolved.
调用 methodName 时我什么都不做。上面的代码不起作用。它说 methodName 无法解析。
回答by Rahul Jain
You can Use PowerMock.createmock() for Mocking your Class Where method is There. For e.g you have ClassA and methodA which is a Void Method. Then You can Mock it in a below way:
您可以使用 PowerMock.createmock() 来模拟您的类 Where 方法。例如,你有 ClassA 和 methodA,这是一个 Void 方法。然后你可以通过以下方式模拟它:
A a = PowerMock.CreateMock(A.class);
a.methodA();
PowerMock.replay(a);
Note : in above case method a is void That's the reason EasyMock.expect is not return;
注意:在上述情况下,方法 a 是无效的,这就是 EasyMock.expect 不返回的原因;
回答by aminator
if you want to mock a non-static method you need to specify the mock object:
如果要模拟非静态方法,则需要指定模拟对象:
public class Name{
public void methodName{
...
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest({Name.class})
public class TestClass{
@Test
public void testMethodName(){
Name myName = PowerMockito.mock(Name.class);
PowerMockito.doNothing().when(myName).methodName();
//some when calls after this and assert later on
}
}
回答by Romski
I'm not at an IDE at the moment, but I think you can do this:
我目前不在 IDE 中,但我认为您可以这样做:
final Name name = mock(Name.class);
doNothing().when(name).methodName();