如何在junit4中使用PowerMockito模拟返回void的公共静态方法

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

我在模拟返回 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 并且无法抑制其他方法。

java static junit4 void powermockito
1个回答
1
投票

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

@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();
            }
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.