【问题标题】:TestRestTemplate is returning 415 Unsupported Media Type for POST call on IntelliJTestRestTemplate 正在为 IntelliJ 上的 POST 调用返回 415 Unsupported Media Type
【发布时间】:2019-10-18 18:50:28
【问题描述】:

我正在为我的 Spring Boot 2 应用程序编写功能测试。

我使用TestRestTemplate 进行功能测试。它适用于 GET API。但现在为了测试 POST API,它返回 415 Unsupported Media Type。我正在传递值为 application/json 的 Content-Type 和 Accept 标头。

只有在 IntelliJ 19 上运行测试时才会发生这种情况。它在命令行上运行良好。我正在使用 Gradle 构建工具。

@RestController
@RequestMapping("Path/rest")    
public class Controller {
    @PostMapping(value = "/api", produces = "application/json", consumes = "application/json")
    public ResponseEntity<Response> getResponse(
    @RequestBody Request request,
    @RequestHeader(name = "Transaction-GUID", required = false) String transactionGUIDheader, HttpServletRequest request)
    throws InvalidInputException, ExternalServiceGenericException {

    Response response = service.getResponse(request, transactionGUID);

    return new ResponseEntity<>(response, HttpStatus.OK);
}

功能测试:

@ActiveProfiles(FUNCTIONAL_TEST)
@SpringBootTest (webEnvironmentSpringBootTest.WebEnvironment.DEFINED_PORT)
@ExtendWith({SpringExtension.class})
@AutoConfigureWireMock(port = 9000)
public class ControllerFunctionalTest {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    protected TestRestTemplate testRestTemplate;

    @BeforeEach
    public void setup() {
        WireMock.reset();
    }

    @Test
public void testControllerPost(){

   HttpEntity<Reqeust>  request = createRq(String str1, String str2);
   callWiremock();
   String url = "http://localhost:8080/Path/rest/api";
   ResponseEntity<Response> response =
        testRestTemplate.postForObject(url, request, Response.class);

    assertNotNull(response);
}

【问题讨论】:

标签: java spring-boot intellij-idea


【解决方案1】:

只需将内容类型放在标题中(在 http 实体中)。


  MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
  headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
  HttpEntity httpEntity = new HttpEntity(headers);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2014-01-21
    相关资源
    最近更新 更多