How to mock a method that returns `Mono<Void>`
Asked Answered
W

4

21

How to mock a method that returns Mono<Void>?

I have this method that returns Mono<Void>

public Mono<Void> deleteMethod(Post post) {

        return statusRepository.delete(post);
    }

In my test class I want to do something like this

given(statusRepository.delete(any(Post.class))).willReturn(Mono.empty());

Is there any better way to do this?

Can someone help me?

Thanks.

Weisbrodt answered 23/7, 2019 at 19:58 Comment(4)
Are you facing any specific issues?Pneumonectomy
No, Initially I got a null mono error I thought Mono.empty() was causing the error, but something else was the reason for null mono. Now, I just wanted to make sure what I was doing is correct.Weisbrodt
As option you can use PublisherProbe<Void> probe = PublisherProbe.empty(); probe. mono(); Example from projectreactor.io/docs/core/release/reference/…Cercus
Post your test cases so that we can take a closer look and suggest improvementsPneumonectomy
F
21

This is possible using Mockito.when:

Mockito.when(statusRepository.delete(any(Post.class)).thenReturn(Mono.empty());

...call the method and verify...

Mockito.verify(statusRepository).delete(any(Post.class));
Firehouse answered 2/9, 2019 at 19:53 Comment(0)
R
2

I do it like this when I don't want to have an empty mono as result.

when(statusRepository.delete(any(Post.class))).thenReturn(Mono.just("").then());
Retrad answered 8/7, 2022 at 11:30 Comment(0)
B
0

I was also able to do this without using Mono.empty so the reactive chain would complete by creating a mock object of type void. Below is a code example (written in Kotlin and using mockito-kotlin, but should be applicable to mockito as well):

val mockVoid: Void = mock()

whenever(statusRepository.delete(any(Post::class.java)).thenReturn(mockVoid)

Bedstraw answered 14/9, 2021 at 22:45 Comment(0)
F
0

If you use Mono.empty(), a mapping or any pipeline is not executed. A better option is to use:

when(service.method()).thenReturn(Mono.just(mock(Void.class)));
Footboy answered 27/5 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.