Spring-Webflux: Handler function unit test is throwing UnsupportedMediaTypeStatusException

Publish date: 2024-05-17

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.

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobG9sZmyGc4GOrKeroZ6cerixwZ%2BjrrBdna6vsMueqWaepaOwtbXOp2SuppmperWx0q1koqtdqbWzu9aipaBlpaPAtrzPqKmtnZSisqW1wK2wqZ2jqa61wQ%3D%3D