spring-bootmockitojunit-jupiter

Mockito: How to mock a method with Mono<> in param and return types


I am working with Junit5 Jupiter and mockito. I have added the mockito extension on top of my test class: @ExtendWith(MockitoExtension.class).

This piece of code does not work in a test keeps failing:

MyService myService = mock(MyService.class);
when(myService.get(Mono.just("TEXT"))).thenReturn(Mono.just(new BusinessObject("blabla")));

The error is

Strict stubbing argument mismatch. Please check:
 - this invocation of 'get' method:
    myService.get(
    MonoJust
);
    -> at com.myapp.service.CustomerService.getCustomersIds(CustomerService.java:59)
 - has following stubbing(s) with different arguments:
    1. myService.get(
    MonoJust
);

How can I mock a method that takes a Mono<String> as input and that returns another Mono<BusinessObject> in output?


Solution

  • I finally found a solution by using thenAnswer().

    when(myService.get(any())).thenAnswer(invocation -> {
        Mono<String> monoInputParam = invocation.getArgument(0);
        // Here, build the output business object according to what you get in input param
        BusinessObject businessObject = businessObjectsMap.get(monoInputParam.block())
        return Mono.just(businessObject);
    });
    

    This way, my mock is "dynamic" because I can return something different according to the input param.

    businessObjectsMap is a Map<String, BusinessObject> prepared in advance.