junit 如何用PowerMockito模拟重载的返回void的公共静态方法

kx1ctssn  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(174)

我在模拟一个返回void的公共静态方法时遇到了一个问题。
这是我到目前为止所拥有的:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheUtilsClass.class)
public class MyTest {
    @Test
    public void theTest() {
        PowerMockito.mockStatic(TheUtilsClass.class);
        PowerMockito.doThrow(new RuntimeException.class).when(TheUtilsClass.class, "methodToBeMocked", any(FirstParam.class), any(SecondParam.class));
    }
}

这不起作用,因为“methodToBeMocked”被重载了几次。相反,我得到了异常TooManyMethodsFoundException,我无法抑制其他方法。

xpcnnkqh

xpcnnkqh1#

我自己找到了解决方案,但在网上找不到。实际上,我只是创建了一个Answer,它抛出了所需的异常,就是这样:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TheUtilsClass.class)
public class MyTest {
    @Test
    public void theTest() {
        PowerMockito.mockStatic(BeanUtils.class, new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                throw new RuntimeException();
            }
        });
    }
}

相关问题