问题描述
我有一个方法可以模拟抛出的异常,以便输入catch语句:
I have a method where I'd like to mock an exception being thrown so that the catch statement is entered:
public static String func(String val) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
return Base64.encode(md5.digest(val.getBytes()));
} catch (NoSuchAlgorithmException toCatch) {
return "*";
}
}
我写的测试是这样的:
@Test
public void testFunc() throws Exception {
MessageDigest md5 = PowerMockito.mock(MessageDigest.class);
PowerMockito.when(md5.getInstance(anyString())).thenThrow(new NoSuchAlgorithmException());
Assert.assertEquals("*", func("in"));
}
但是我得到了:
java.security.NoSuchAlgorithmException: MessageDigest not available
PowerMockito.when()
行上的
.这意味着异常已通过但未被捕获?我在做什么错了?
on the PowerMockito.when()
line. Which implies the exception has been through, but not caught? What am I doing wrong?
更新:我已经尝试了以下修改
Update:I have tried the following modifications
@PrepareForTest({MessageDigest.class})
@Test
public void testFunc() throws Exception {
PowerMockito.mockStatic(MessageDigest.class);
PowerMockito.when(MessageDigest.getInstance(anyString())).thenThrow(new NoSuchAlgorithmException());
Assert.assertEquals("*", testFunc("in"));
}
这将导致该函数在不触发异常的情况下运行.
This causes the function to run without triggering the exception.
这:
@PrepareForTest({MessageDigest.class})
@Test
public void testFunc() throws Exception {
PowerMockito.mockStatic(MessageDigest.class);
MessageDigest md5 = PowerMockito.mock(MessageDigest.class);
PowerMockito.doThrow(new NoSuchAlgorithmException()).when(md5, "getInstance", anyString());
Assert.assertEquals("*", func("in"));
}
仍然不调用catch语句,类似于我之前获得的内容.
Still doesn't invoke the catch statement, similar to what I was getting before.
推荐答案
由于MessageDigest
是Java系统类,因此您需要按照以下方式分别处理它们:"> https://github.com/powermock/powermock/wiki/Mock-System
As MessageDigest
is a Java system class, you need to deal with them differently as per: https://github.com/powermock/powermock/wiki/Mock-System
因此,在@PrepareForTest
批注中声明测试类,如下所示:@PrepareForTest({MessageDigest.class, MyTest.class})
So declare the test class in the @PrepareForTest
annotation as follows:@PrepareForTest({MessageDigest.class, MyTest.class})
不确定此注释是否按照您的示例作为方法级别使用,但应在类级别使用:
Not sure if this annotation works as method level as per your example, but it should at class level:
@RunWith(PowerMockRunner.class)
@PrepareForTest({MessageDigest.class, MyTest.class})
public class MyTest {
这篇关于无法使用嘲笑引发异常-未捕获引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!