我正在尝试向处理程序函数编写单元测试,我遵循了Spring项目中的example。谁能帮我解释一下为什么下面的测试抛出UnsupportedMediaTypeStatusException
谢谢
处理程序函数
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);
}测试类
@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);
}
}错误消息:应用程序:期望"expectComplete“失败(期望: onComplete();实际: onError(org.springframework.web.server.UnsupportedMediaTypeStatusException: 415 UNSUPPORTED_MEDIA_TYPE”内容类型‘应用程序/八位字节流’bodyType=com.example.demo.Person不支持“)
发布于 2019-06-22 00:36:51
我发现我在模拟请求中错过了.contentType(MediaType.APPLICATION_JSON)。
MockServerWebExchange.from(
MockServerHttpRequest.post("/api/create").contentType(MediaType.APPLICATION_JSON)
.body(gson.toJson(Person.builder().firstName("Jon").lastName("Doe").build())));修复了我的问题。
https://stackoverflow.com/questions/56467925
复制相似问题