没有内容类型,无法测试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一起使用。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...