Search code examples
unit-testingpowermockito

PowerMockito whenNew thenReturn not working


I have two classes like given below:

public class example
{
    public void method()
    {
        System.out.println("Shouldn't be here!");
    }
}
public class lol
{
    public void yes()
    {
        example obj = new example();
        obj.method();
    }
}

Following is the test I used

@RunWith(PowerMockRunner.class)
@PrepareForTest({example.class,lol.class})
class examplemainTest
{
    @Test
    void yes() throws Exception
    {
        example obj = PowerMockito.mock(example.class);

        PowerMockito.whenNew(example.class).withAnyArguments().thenReturn(obj);

        //PowerMockito.whenNew(example.class).withNoArguments().thenReturn(obj);

        obj.method();

        example aa = new example();
        aa.method();  //line 1

        lol bb = new lol();
        bb.yes();   //line 2
    }
}

line 1 and 2 still calling the original lol::method(). Please, help me out, I don't know what am I missing, doing tests for the first time. I also tried whenNew().withNoArguments() so I put it in the comments just so you know.


Solution

  • I researched a little bit, here whenNew does not mock the the methods but the constructor of the class provided (example.class). So if you define a constructor inside example.classthat will be replaced by the constructor of your mock class but example::method() invoked here is the original one. So now the question is how do we handle this situation, well I found it here take a look.