我有一个像
public interface WithMD5Calculator{
default String getMd5(){
try{
MessageDigest md = MessageDigest.getInstance("MD5");
//... not important
}catch(NoSuchAlgorithmException e){
//... do some extra stuff and throw wrapped in ServiceException
}
}
// rest of code not important
}
并测试应该验证异常处理:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MessageDigest.class)
public class WithMD5Calculator{
@Test
public void shouldHandleNSAEx(){
PowerMockito.mockStatic(MessageDigest.class);
Mockito.when(MessageDigest.getInstance("MD5")).thenThrow(new NoSuchAlgorithmException("Throwed"));
WithMD5Calculator sut = new WithMD5Calculator(){};
ExceptionAssert.assertThat(()-> sut.getMd5())
.shouldThrow(ServiceException.class);
// some more checks
}
}
但是
ServiceException
没有被抛出。看起来 MessageDigest.getInstance
没有被 mock 。任何想法?
最佳答案
将 WithMD5Calculator 添加到 PrepareForTest 列表可能会解决您的问题。
关于java - 在java 8接口(interface)的默认方法中模拟静态方法调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34153483/