Skip to content

MockMvcWebTestClient cannot handle null in ResponseBody #33977

@gustavhagland

Description

@gustavhagland

When using MockMvcWebTestClient.bindToController to a controller with an annotated endpoint which returns null. Then the WebTestClient crashes when calling expectBody with the following message:

Content type 'application/octet-stream' not supported for bodyType=java.time.LocalDate
org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/octet-stream' not supported for bodyType=java.time.LocalDate
	at org.springframework.web.reactive.function.BodyExtractors.readWithMessageReaders(BodyExtractors.java:205)
	Suppressed: The stacktrace has been enhanced by Reactor, refer to additional information below: 
Error has been observed at the following site(s):
	*__checkpoint ⇢ Body from GET /date [DefaultClientResponse]

Expected behaviour is for it not to crash and for getResponseBody to return null.

Controller class:

package com.example.demo;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@RestController
public class DemoController {

    @GetMapping(value = "date", produces = MediaType.APPLICATION_JSON_VALUE)
    public LocalDate date() {
        return null;
    }
}

Test class:

package com.example.demo;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.client.MockMvcWebTestClient;

import java.time.LocalDate;

class DemoControllerTest {

    @Test
    void mvcTest() {
        var client = MockMvcWebTestClient.bindToController(new DemoController())
                .configureClient()
                .build();

        var res = client.get()
                .uri("/date")
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectBody(LocalDate.class)
                .returnResult()
                .getResponseBody();

        Assertions.assertThat(res).isNull();
    }
}

Repository with reproducible example: https://github.com/gustavhagland/mock-mvc-issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions