【发布时间】: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);
}
【问题讨论】:
-
通常,当您发送与请求的实际正文不匹配的
Content-Type标头时,会返回 HTTP 415。比如用HTTP GET方法发送Content-Type等
标签: java spring-boot intellij-idea