PowerMockito when New thenReturn not work

问题描述 投票:0回答:1

我有两个类似下面的类:

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

以下是我使用的测试

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

第1行和第2行仍在呼叫原始的lol::method()。请帮帮我,我不知道我缺少什么,第一次进行测试。我也尝试过whenNew().withNoArguments(),所以我将其放入注释中,以便您知道。

unit-testing powermockito
1个回答
0
投票

尽管doNothing应该是void方法的默认行为,但尝试显式覆盖预期的方法。

@RunWith(PowerMockRunner.class)
@PrepareForTest({lol.class}) //prepare the class creating the new instance of example for test, not the example itself.
public class examplemainTest {
    @Test
    public void yes() throws Exception {
        //Arrange
        example obj = Mockito.mock(example.class);
        doNothing().when(obj).method(); //override void member to do nothing

        //mocking initialization of example class within lol class
        PowerMockito.whenNew(example.class).withNoArguments().thenReturn(obj);

        lol bb = new lol();

        //Act            
        bb.yes();

        //Assert
        verify(obj, times(1)).method();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.