Spring Webflux中的单元测试重试,模拟响应



在单元测试重试期间,mock的响应似乎被缓存了,或者很可能我做错了什么。

我正在尝试请求一些东西,如果发生错误,请重试两次,延迟1秒。

public Mono<Object> someMethod(String someParam) {
return someInjectedService.doSomething(someParam)
.doOnError(ex -> System.out.println(ex + ": " + System.currentTimeMillis()))
.retryWhen(Retry.fixedDelay(2, Duration.ofSeconds(1)).filter(ex -> ex instanceof SomeCustomException))
.doOnSuccess(result -> doSomethingOnSuccess(result));
}

我的测试:

@Test
void testshouldRequestThrice_whenErrorOccurs() {
// Given
String someParam = "testParam";
when(someInjectedService.doSomething(someParam))
.thenReturn(Mono.error(new SomeCustomException("SomeCustomException"))) // 1st response
.thenReturn(Mono.error(new SomeCustomException("SomeCustomException"))) // 2nd response
.thenReturn(Mono.just("SomeValidResponse")); // 3rd valid response
// When
var result = testService.someMethod(someParam).block();
// Then
// Initial request, followed by two retries
verify(someInjectedService, times(3)).doSomething(someParam);
}

这里CCD_ 1是一个mock。我的计划是返回两次异常,在第三次请求时返回有效响应。但我得到的是:

org.mockito.exceptions.verification.ToFewActualInvocations:someInjectedService.doSomething("testParam"(;

通缉3次:->在shouldRequestThrice_whenErrorOccurs(test.java:138(

但是是1次:

虽然我确实看到了.doOnError(ex -> System.out.println(ex + ": " + System.currentTimeMillis()))块的3个打印,但我觉得实际的请求只发送了一次。

提前谢谢你,

someInjectedService.doSomething(...)在技术上实际上只会被调用一次。

您可以使用Mono.defer(() -> someInjectedService.doSomething(someParam)),以确保再次有效地调用该方法,这将使您的测试通过

最新更新