Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java 8接口中默认方法中的模拟静态方法调用_Java_Java 8_Powermockito - Fatal编程技术网

java 8接口中默认方法中的模拟静态方法调用

java 8接口中默认方法中的模拟静态方法调用,java,java-8,powermockito,Java,Java 8,Powermockito,我有一个像 public interface WithMD5Calculator{ default String getMd5(){ try{ MessageDigest md = MessageDigest.getInstance("MD5"); //... not important }catch(NoSuchAlgorithmException e){ //... do some

我有一个像

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
未被模拟


有什么想法吗?

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

如果我想检查是否调用了方法或静态类的更一般的行为,请验证
。在我的例子中,我不需要验证行为,但需要更改方法的行为。一个想法是:当使用PowerMockito模拟方法时,您可能希望使用PowerMockito来存根方法(例如,PowerMockito.when(…)。然后抛出(…)。Mockito怎么知道您调用了静态方法呢?PowerMockito中的
when
方法只是Mockito库中
when
的包装器。PowerMockito的“魔力”在于,它通过注释
@PrepareForTest
将带有static的类准备为Mockito“可模拟”的类。Powermock文档说,java系统/引导类加载器加载的模拟类有点不同:。但我并没有成功地让Mockito采用这种方法。