简体   繁体   English

如何在powermock中模拟void方法

[英]how to mock a void method in powermock

How to mock a void method which is non-static, non-finalThe signature of method is as below.如何模拟一个非静态、非 final 的 void 方法方法的签名如下。 I'm using Powermockito.我正在使用 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.调用 methodName 时我什么都不做。 the above code is not working.上面的代码不起作用。 it says methodName cannot be resolved.它说 methodName 无法解析。

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
    }
}

You can Use PowerMock.createmock() for Mocking your Class Where method is There.您可以使用 PowerMock.createmock() 来模拟您的类 Where 方法。 For eg you have ClassA and methodA which is a Void Method.例如,你有 ClassA 和 methodA,这是一个 Void 方法。 Then You can Mock it in a below way:然后你可以通过以下方式模拟它:

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 不返回的原因;

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM