【发布时间】:2019-08-30 17:16:07
【问题描述】:
我有一个方法想模拟抛出的异常,以便输入 catch 语句:
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() 线上。这意味着异常已经通过,但没有被捕获?我做错了什么?
更新: 我尝试了以下修改
@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"));
}
这会导致函数在不触发异常的情况下运行。
还有这个:
@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 语句,类似于我之前得到的。
【问题讨论】:
标签: java unit-testing junit mocking powermockito