英文:
How to mock overloaded public static method which returns void with PowerMockito
问题
以下是您要翻译的代码部分:
我遇到了一个问题,需要模拟一个返回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"
,应该替换为"methodToBeMocked"
,因为它是实际的方法名称。
英文:
I got a problem mocking a public static method which returns void.
This is what I have so far:
@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));
}
}
And this does not work because "methodToBeMocked" is overloaded several times. Instead I got the exception TooManyMethodsFoundException where I could not suppress other methods.
答案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();
}
});
}
}
英文:
I have found solution myself, but could not find it online. Actually I just have created an Answer which throws the needed exception and that's it:
@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();
}
});
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论