Spring-Webflux: Handler Function Unit Test Is Throwing Unsupportedmediatypestatusexception

I am trying to write Unit test to the handler function, I followed the example from the Spring project. Can someone help me why the following test is throwing UnsupportedMediaTypeStatusException?

Thanks

Handler function

public Mono<ServerResponse> handle(ServerRequest serverRequest) {
        log.info("{} Processing create request", serverRequest.exchange().getLogPrefix());

        return ok().body(serverRequest.bodyToMono(Person.class).map(p -> p.toBuilder().id(UUID.randomUUID().toString()).build()), Person.class);
    }

Test Class

@SpringBootTest
@RunWith(SpringRunner.class)
public class MyHandlerTest {

    @Autowired
    private MyHandler myHandler;
    private ServerResponse.Context context;

    @Before
    public void createContext() {
        HandlerStrategies strategies = HandlerStrategies.withDefaults();
        context = new ServerResponse.Context() {
            @Override
            public List<HttpMessageWriter<?>> messageWriters() {
                return strategies.messageWriters();
            }

            @Override
            public List<ViewResolver> viewResolvers() {
                return strategies.viewResolvers();
            }
        };
    }

    @Test
    public void handle() {

        Gson gson = new Gson();

        MockServerWebExchange exchange = MockServerWebExchange.from(
                MockServerHttpRequest.post("/api/create")
                        .body(gson.toJson(Person.builder().firstName("Jon").lastName("Doe").build())));

        MockServerHttpResponse mockResponse = exchange.getResponse();

        ServerRequest serverRequest = ServerRequest.create(exchange, HandlerStrategies.withDefaults().messageReaders());

        Mono<ServerResponse> serverResponseMono = myHandler.handle(serverRequest);

        Mono<Void> voidMono = serverResponseMono.flatMap(response -> {
            assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
            boolean condition = response instanceof EntityResponse;
            assertThat(condition).isTrue();
            return response.writeTo(exchange, context);
        });

        StepVerifier.create(voidMono)
                .expectComplete().verify();

        StepVerifier.create(mockResponse.getBody())
                .consumeNextWith(a -> System.out.println(a))
                .expectComplete().verify();

        assertThat(mockResponse.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);

    }
}

Error Message: java.lang.AssertionError: expectation "expectComplete" failed (expected: onComplete(); actual: onError(org.springframework.web.server.UnsupportedMediaTypeStatusException: 415 UNSUPPORTED_MEDIA_TYPE "Content type 'application/octet-stream' not supported for bodyType=com.example.demo.Person"))

1

1 Answer

I found that I missed .contentType(MediaType.APPLICATION_JSON) to my mock request.

MockServerWebExchange.from(
                MockServerHttpRequest.post("/api/create").contentType(MediaType.APPLICATION_JSON)
                        .body(gson.toJson(Person.builder().firstName("Jon").lastName("Doe").build())));

fixed my issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest