PowerMockito whenNew thenReturn 不工作

PowerMockito whenNew thenReturn not working

我有两个 类,如下所示:

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() 所以我把它放在评论里让你知道。

我研究了一下,这里whenNew没有模拟方法,而是模拟了class提供的构造函数(example.class)。因此,如果您在 example.class 中定义一个构造函数,它将被模拟 class 的构造函数替换,但此处调用的 example::method() 是原始构造函数。 那么现在的问题是我们如何处理这种情况,好吧我找到了看看。