如何解决没有内容类型,无法测试PUT请求
我想知道,如何通过使用Spring的WebTestClient来测试带有正文但没有Content-Type的PUT请求?
我的测试如下:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class StackOverflowTest {
@Autowired
WebTestClient webTestClient;
@Test
void testPUT() {
// GIVEN
...
// WHEN
webTestClient.put()
.uri("/foo/bar")
.bodyValue("<abc></abc>")
.exchange()
// THEN
.expectStatus().isCreated();
...
}
}
,但是客户端随后将Content-Type自动设置为text/plain;charset=UTF-8
。通常,这是件好事,但我想测试一下这种情况(不带Content-Type的客户端请求)。我可以使用其他客户端,但是也许有一种我不知道的方法或解决方法。
解决方法
我不确定是否可以使用WebTestClient
来实现。我自己尝试了几种方法自定义ExchangeFilterFunction
,以不同的方式设置正文,但总是填充Content-Header
。
但是有效的是,如果您不向请求提供任何.bodyValue()
或.body()
,则不会获得标头。
如果您好奇Content-Type
标头中填充的位置,请查看writeWithMessageWriters
的{{1}}方法:
BodyInserters
您会看到总是从邮件中检索private static <M extends ReactiveHttpOutputMessage> Mono<Void> writeWithMessageWriters(
M outputMessage,BodyInserter.Context context,Object body,ResolvableType bodyType,@Nullable ReactiveAdapter adapter) {
Publisher<?> publisher;
if (body instanceof Publisher) {
publisher = (Publisher<?>) body;
}
else if (adapter != null) {
publisher = adapter.toPublisher(body);
}
else {
publisher = Mono.just(body);
}
MediaType mediaType = outputMessage.getHeaders().getContentType();
return context.messageWriters().stream()
.filter(messageWriter -> messageWriter.canWrite(bodyType,mediaType))
.findFirst()
.map(BodyInserters::cast)
.map(writer -> write(publisher,bodyType,mediaType,outputMessage,context,writer))
.orElseGet(() -> Mono.error(unsupportedError(bodyType,mediaType)));
}
。
我想它应该与MediaType
一起使用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。