简体   繁体   中英

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. I'm using 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.

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. For eg you have ClassA and methodA which is a Void Method. 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;

I'm not at an IDE at the moment, but I think you can do this:

final Name name = mock(Name.class);
doNothing().when(name).methodName();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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