user3595026
user3595026

Reputation: 629

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

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.

Upvotes: 21

Views: 25775

Answers (4)

Antonio A. Pinedo
Antonio A. Pinedo

Reputation: 11

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

Upvotes: 1

GeBeater
GeBeater

Reputation: 173

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

Upvotes: 2

Alan Yeung
Alan Yeung

Reputation: 300

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)

Upvotes: 0

Gustavo Ballest&#233;
Gustavo Ballest&#233;

Reputation: 326

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

Upvotes: 21

Related Questions