title: Mocking a WebClient post when there's a request body
body: <p>There are several questions with helpful answers about mocking a WebClient object. But I still have problems when doing a post with a body. I'm just using <strong>Mockito</strong> not <strong>mockwebserver</strong>. </p>
  
  <p>This is the method I'm testing:</p>
  
  <pre><code>public class RestClient extends BaseRestClient {
   ...
   public &lt;T,G&gt; Mono&lt;T&gt; post(String url, G req, Class&lt;T&gt; resp) throws IOException {
          Mono&lt;T&gt; response = null;
  
          response = this.getWebClient().post()
                      .uri(url)
                      .header(HttpHeaders.CONTENT_TYPE,JSON_CONTENT_TYPE)
                      .accept(MediaType.APPLICATION_JSON)
                      //.body(BodyInserters.fromObject(req))
                      .header(HttpHeaders.AUTHORIZATION, BEARER + token)
                      .retrieve()
                      .bodyToMono(resp).log();
  
          return response.map(resp::cast);
      }
   ...
  </code></pre>
  
  <p>Notice the commented out body line.</p>
  
  <p>And this is the test which works fine with the code above- again notice the commented out line in the test:</p>
  
  <pre><code>@Mock
  WebClient webClient;
  
  @Mock
  WebClient.RequestBodyUriSpec requestBodyUriSpec;
  
  @Mock
  WebClient.RequestHeadersSpec requestHeadersSpec;
  
  @Mock
  WebClient.RequestBodySpec requestBodySpec;
  
  @Mock
  WebClient.ResponseSpec responseSpec;
  
  @InjectMocks
  RestClient restClient;
  
  @Test
      public void postTest() throws IOException {
          when(webClient.post()).thenReturn(requestBodyUriSpec);
          when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec);
          when(requestBodySpec.header(any(),any())).thenReturn(requestBodySpec);
          when(requestBodySpec.accept(any())).thenReturn(requestBodySpec);
          when(responseSpec.bodyToMono(ArgumentMatchers.&lt;Class&lt;String&gt;&gt;notNull()))
                  .thenReturn(Mono.just("resp"));
  
          //when(requestBodySpec.body(any())).thenReturn(requestHeadersSpec);
          when(requestBodySpec.retrieve()).thenReturn(responseSpec);
  
          restClient.post("http://sampleurl",Object.class, Object.class);
      }
  </code></pre>
  
  <p>Again, everything works fine. But if I put the commented out line back in the code, meaning there's a body to this post, and mock the body by putting the commented out line back in the test, then I'll get <strong>NullPointerException</strong> on <strong>.retrieve()</strong> in the code. Just like I'm missing an object to mock.</p>
  
  <p>I even mocked .retrieve() for <strong>requestHeadersSpec</strong> and <strong>requestBodyUriSpec</strong>:</p>
  
  <pre><code>when(requestHeadersSpec.retrieve()).thenReturn(responseSpec);
  when(requestBodyUriSpec.retrieve()).thenReturn(responseSpec);
  </code></pre>
  
  <p>And still no success. Any ideas what's wrong there?</p>