【问题标题】:Cannot apply when mocking spring repository delete with Mockito [duplicate]使用 Mockito 模拟弹簧存储库删除时无法应用 [重复]
【发布时间】:2018-11-24 12:32:20
【问题描述】:

我搜索了所有我能想到的解决方案,但措辞很困难。

我有一个在 Spring Repository 上调用 delete 的单元测试。回购定义为:

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

不确定如何继续。

【问题讨论】:

  • 请粘贴错误文本,图片在防火墙后不可见。
  • Exception 是一个检查异常。除非你的 delete() 方法声明了 throws Exception,否则你不能从那里扔掉它。使用RuntimeException
  • @Arkadiy 切换到 RuntimeException。没有变化。
  • 好的,那么我需要查看错误的文本。图片被过滤掉了:(
  • @Arkadiy 添加。感谢您的关注。

标签: java unit-testing mockito


【解决方案1】:

如前所述,问题实际上是关于返回是无效的,而不是关于传递的参数类型。根据How to make mock to void methods with Mockito,我改代码如下:

    Mockito.doThrow(new RuntimeException()).when(fileConfigurationRepository).delete(GlobalConfiguration.CUSTOM_LOGO_ID);

这就解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2022-12-11
    • 2018-05-03
    • 2014-02-18
    • 2019-10-04
    相关资源
    最近更新 更多