gpt4 book ai didi

java - 模拟匿名函数

转载 作者:行者123 更新时间:2023-11-30 06:59:45 27 4
gpt4 key购买 nike

我在编写 jUnits 时被 Lambda 表达式卡住了。

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

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

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

最佳答案

对我来说,@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 无法对正确的方法进行 stub 有关。

最终解决方案:

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

我可以将这个添加到原始问题中吗:Why isn't the Matcher able to resolve to the one-argument method?

关于java - 模拟匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31173401/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com