在java 8接口中使用默认方法调用静态方法

时间:2015-12-08 10:27:34

标签: java java-8 powermockito

我有一个像

这样的界面
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没有被嘲笑。

有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

将WithMD5Calculator添加到PrepareForTest列表可能会解决您的问题。