模拟匿名函数 [英] Mocking anonymous function

查看:47
本文介绍了模拟匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写 jUnits 并被 Lambda 表达式卡住了.

I'm writing jUnits and got stuck with the Lambda expressions.

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

Is there a way to mock anonymous function?

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

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

In the above code, I'm trying to mock retryTemplate. retryTemplate is of type - org.springframework.retry.support.RetryTemplate

推荐答案

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

For me the solution of @encrest didn't work.

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 个匹配器).另请参阅无意义的.

This error seems a bit stupid, because .execute() should work with only 1 argument (and thus 1 matcher). See also non-sensical.

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

When looking into RetryTemplate sources, there are 4 .execute() methods. With one with 3 arguments. So I guess it is related to Matchers not being able to stub the right method.

最终解决方案:

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 无法解析为单参数方法?

Can I add this to the original question: Why isn't the Matcher able to resolve to the one-argument method?

这篇关于模拟匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆