Search code examples
groovyreactive-programmingspockproject-reactor

How to mock Mono.create


I'm using the spock framework and need to return a mocked Mono from a Mono.create(..)

I've tried:

GroovyMock(Mono)

as well as

GroovyMock(Mono, global:true)
1 * Mono.create(_ as MonoSink) >> Mono.just(returnedValue)

But I get the message that there were too few assertions for the above code.

Here is the actual Mono.create code

Mono.create{ sink -> 
    myAPISoap.getStuffAsync(
            username, 
            password, 
            info, 
            { outputFuture -> 
                try {
                    sink.success(outputFuture.get())
                } catch(Exception e){
                    sink.error(e)
                } 
            }
    )
}

Solution

  • In Spock, you can only mock static methods of Groovy classes, not Java classes. You can use PowerMock(ito) for Java classes in this case. Then your problem can be solved as follows:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Mono.class)
    public class MonoTest {
        @Test
        public void test() {
            //given:
            PowerMockito.spy(Mono.class);
            Mockito.when(Mono.create(...)).thenReturn(null);
    
            //when:
            Mono<?> mono = Mono.create(...);
    
            //then:
            PowerMockito.verifyStatic(Mono.class, Mockito.times(1));
            Mono.create(...);
    
            //assertions
        }
    }