【问题标题】:Mocking anonymous function模拟匿名函数
【发布时间】:2015-07-01 23:39:22
【问题描述】:

我正在编写 jUnits,但被 Lambda 表达式卡住了。

有没有办法模拟匿名函数?

  return retryTemplate.execute(retryContext -> {
     return mockedResponse;
  });

在上面的代码中,我试图模拟retryTemplateretryTemplate 的类型是 - org.springframework.retry.support.RetryTemplate

【问题讨论】:

    标签: java spring mockito


    【解决方案1】:

    对我来说,@encrest 的解决方案不起作用。

    RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
    Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class))).thenReturn(mockedResponse);
    

    我收到了这个错误:

    org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
    Invalid use of argument matchers!
    3 matchers expected, 1 recorded:
    -> at test1(ServiceTest.java:41)
    
    This exception may occur if matchers are combined with raw values:
        //incorrect:
        someMethod(anyObject(), "raw String");
    When using matchers, all arguments have to be provided by matchers.
    For example:
        //correct:
        someMethod(anyObject(), eq("String by matcher"));
    
    For more info see javadoc for Matchers class.
    
    
        at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:164)
    

    这个错误似乎有点愚蠢,因为.execute() 应该只使用 1 个参数(因此只有 1 个匹配器)。另见non-sensical

    查看RetryTemplate 源时,有4 个.execute() 方法。一个有 3 个参数。所以我想这与 Matchers 无法存根正确的方法有关。

    最终解决方案:

    RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
    Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class), Matchers.any(RecoveryCallback.class), Matchers.any(RetryState.class))).thenReturn(mockedResponse);
    

    我可以将这个添加到原来的问题中:为什么 Matcher 不能解析为单参数方法?

    【讨论】:

    • 哇,非常感谢!我仍然不知道为什么这不起作用。我没有想出这个解决方案。非常好,谢谢!
    • 为什么 Matcher 不能解析到单参数方法? 问题实际上是因为,RetryTemplate.execute 用你的 matcher 对象调用 doExecute,并且 null对于其余的。这是不允许的,因为您可以混合匹配器和原始值
    【解决方案2】:

    假设“retryTemplate”是某个 bean“myBean”中的依赖项,我将使用依赖注入来模拟使用 Mockito 的“retryTemplate.execute”方法并将其配置为接受任何参数:

    RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
    Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class))).thenReturn(mockedResponse);
    myBean.setRetryTemplate(mockRetryTemplate);
    

    如果我只是想模拟一个参数恰好是 lambda 的方法的参数,我可能只是创建一个新的 lambda 表达式存根而不是尝试模拟它。

    【讨论】:

    • 执行方法不适用于参数(对象)。它需要不同的参数集。
    • @user1879835 尝试将 Matchers.any() 替换为 Matchers.any(RetryCallback.class)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 2022-07-12
    • 1970-01-01
    • 2021-11-03
    • 2011-04-20
    • 1970-01-01
    相关资源
    最近更新 更多