繁体   English   中英

TestRestTemplate 正在为 IntelliJ 上的 POST 调用返回 415 Unsupported Media Type

[英]TestRestTemplate is returning 415 Unsupported Media Type for POST call on IntelliJ

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

我使用TestRestTemplate进行功能测试。 它适用于 GET API。 但是现在为了测试 POST API,它返回415 Unsupported Media Type 我正在传递 Content-Type 并接受 header ,其值为application/json

只有在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);
}

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM