这个问题在这里已经有了答案:
How to mock void methods with Mockito
(10 个回答)
3年前关闭。
我在谷歌上搜索了所有我能想到的解决方案,但措辞很困难。
我有一个单元测试,它在 Spring 存储库上调用 delete。 repo 定义为:
public interface FileConfigurationRepository extends CasenetRepository<FileConfiguration, String> {}
我正在测试的方法有以下调用:
fileConfigurationRepository.delete(GlobalConfiguration.CUSTOM_LOGO_ID);
其中 GlobalConfiguration.CUSTOM_LOGO_ID 定义为:
public static final String CUSTOM_LOGO_ID = "customLogoId";
所以我写了我的模拟如下:
Mockito.when(fileConfigurationRepository.delete(GlobalConfiguration.CUSTOM_LOGO_ID)).thenThrow(new Exception());
但后来我收到以下错误:
错误文本:
No instance(s) of type variable(s) T exist so that void conforms to T
不确定如何继续。
最佳答案
如上所述,问题实际上是关于返回无效,而不是关于传递的参数类型。根据 How to make mock to void methods with Mockito ,我把代码改成如下:
Mockito.doThrow(new RuntimeException()).when(fileConfigurationRepository).delete(GlobalConfiguration.CUSTOM_LOGO_ID);
这解决了问题。
关于java - 使用 Mockito 模拟 spring 存储库删除时无法应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50862418/