Arczi
Arczi

Reputation: 143

Mockito mock WebClient Json response

I want to mock WebClient in Spring.

public Test getTest(String lanId) {

    return webClient.get()
            .uri("url")
            .retrieve()
            .bodyToMono(Test.class)
            .block();
}

Test method:

@Mock ????
WebClient webClient;

@InjectMocks
TranslateDao translateDao;

@Test
void getUserId() {
    webClient = WebClient.builder().build();

    var ww = translateDao.getTest("qw");
    System.out.println("");
}

When I try without @Mock on webClient I got null pointer. I want to do sth like this:

when(WebClient.sth).thenReturn("{JSON!!}")
var result = translateDao.getTest("test")
assert....

any idea ?

Upvotes: 0

Views: 3120

Answers (2)

jcompetence
jcompetence

Reputation: 8383

My recommendation is to not mock WebClient, but rather use MockWebServer.

If you insist on mocking WebClient, you will need to mock every part of it:

@Mock
private WebClient.RequestBodyUriSpec requestBodyUriMock;
@Mock
private WebClient.RequestHeadersSpec requestHeadersMock;
@Mock
private WebClient.RequestBodySpec requestBodyMock;
@Mock
private WebClient.ResponseSpec responseMock;
@Mock
private WebClient webClient;

@InjectMocks
YourService serviceUsingWebClient;

@Test
void makeAPostRequest() {

    when(requestBodyUriMock.uri(eq("uri"))).thenReturn(requestBodyMock);
    when(requestBodyMock.bodyValue(eq(yourPojoRequestHere))).thenReturn(requestHeadersMock);
    when(webClient.post()).thenReturn(requestBodyUriMock);
    when(requestHeadersMock.retrieve()).thenReturn(responseMock);
    when(responseMock.bodyToMono(YourPojoClass.class)).thenReturn(Mono.just(yourPojoResponse));
}

Upvotes: 1

Alexander Sels
Alexander Sels

Reputation: 26

The question is a little bit confusing since:

  1. You are mocking the Webclient
  2. In your test, you are assigning an actual value to the mock value (this does not seem correct)
  3. In your last example you are trying to mock a static call on WebClient (mockito doesn't support that out of the box)

Is WebClient provided to your class through dependency injection or other means ?

Edit: It seems when you want to mock a WebClient that you will have quite an extensive amount of mocking ahead of you ...

Reference: https://www.baeldung.com/spring-mocking-webclient

Upvotes: 1

Related Questions