Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

514
Vistas
Unit testing retry in Spring Webflux with mocked response

During unit testing retry the response of the mock seems cached, or most probably I am doing something wrong.

I am trying to request something, if error happened then retry twice with delay of 1 second.

  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));
  }

My test:

  @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);
  }

here someInjectedService is a mock. My plan was to return an exception twice, and on third request return valid response. But what I get is:

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

Wanted 3 times: -> at shouldRequestThrice_whenErrorOccurs(test.java:138)

But was 1 time:

While I do see 3 prints from .doOnError(ex -> System.out.println(ex + ": " + System.currentTimeMillis())) block, I feel like the actual request is sent only once.

Thank you in advance,

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

someInjectedService.doSomething(...) will indeed technically be called only once.

You could use Mono.defer(() -> someInjectedService.doSomething(someParam)) instead, to ensure the method is effectively called again, which should make your test pass.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda