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

jaxagkaj  于 10个月前  发布在  Java
关注(0)|答案(1)|浏览(87)

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

blmhpbnm

blmhpbnm1#

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

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

字符串
}

相关问题