为什么这个简单的 Junit 5 测试不起作用

Why this simple Junit 5 test is not working

我正在使用 JUnit 5。调试时,我可以看到我的代码从实现中抛出 FileStorageException 异常。但它给出了这个错误信息:-

org.mockito.exceptions.misusing.UnnecessaryStubbingException: 检测到不必要的存根。 干净且可维护的测试代码需要零不必要的代码。 以下存根是不必要的(单击以导航到相关代码行): 1. -> 在 com.spark.profile.service.ProfileServiceImplTest.testThrowFileStorageExceptionWhenNull(ProfileServiceImplTest.java:67) 请删除不必要的存根或使用 'lenient' 严格。更多信息:UnnecessaryStubbingException class.

的 javadoc

怎么了?如何通过 Junit 5 测试这个异常?

    @Test
void testThrowFileStorageExceptionWhenNull() {
    // act
    when(profileService.storeFile(null, null)).thenReturn(null);
    //assert
    assertThrows(FileStorageException.class,
            () -> {
                profileServiceImpl.storeFile(null, null);
            }
    );
}

UnnecessaryStubbingException 意味着你嘲笑了甚至没有被调用的东西的 return。在你的情况下是 when(profileService.storeFile(null, null)).thenReturn(null);。删除该行应该可以解决您的问题。