Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 650
user2831237 Avatar asked Nov 22 '22 15:11

user2831237


1 Answers

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
    }
}
like image 91
aminator Avatar answered Dec 05 '22 10:12

aminator