RestAssured Post call with body throws an error "java.lang.AssertionError: 1 expectation failed. Expected status code <200> but was <415>."
RestAssured Post call with body throws an error "java.lang.AssertionError: 1 expectation failed. Expected status code <200> but was <415>."
@Test
public void testPost() throws URISyntaxException {
AgencyRequest agencyRequest = new AgencyRequest();
agencyRequest.setConnectorId(1);
agencyRequest.setJobConfig("/usr/local/workspace/test.config.xml");
agencyRequest.setConnectorName("/usr/local/workspace/test.kjb");
agencyRequest.setRequestId(1);
agencyRequest.setTenantId(1);
agencyRequest.setTenantName("Test Tenant");
agencyRequest.setTimeZone("UTC");
String json = new Gson().toJson(agencyRequest);
System.out.println(json);
System.out.println(uri + "/" + ResourceConstants.JOB_CONFIG);
given().
accept(ContentType.JSON).
body(json).
post(new URI(uri + "/" + ResourceConstants.JOB_CONFIG)).
then().
assertThat().
statusCode(HttpStatus.OK_200);
}
如果我 运行 通过选择 post 方法和内容类型作为 json 对 Postman 进行相同的测试并使用正文,它给出的响应状态代码为 200。但是我的单元测试没有通过。在正文中,我曾尝试传递 json 字符串,如您之前所见,我也尝试传递 java 对象,但都失败了。
您需要在发送请求时定义请求的内容类型。考虑进行给定的更改
.contentType(ContentType.JSON)
尝试将这一行添加到代码的顶部:
.log().all()
.config(RestAssured.config().encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
.header()....
这个改动会奏效的,试试吧。
.header("Content-Type", "application/json").contentType(ContentType.JSON).accept(ContentType.JSON)
@Test
public void testPost() throws URISyntaxException {
AgencyRequest agencyRequest = new AgencyRequest();
agencyRequest.setConnectorId(1);
agencyRequest.setJobConfig("/usr/local/workspace/test.config.xml");
agencyRequest.setConnectorName("/usr/local/workspace/test.kjb");
agencyRequest.setRequestId(1);
agencyRequest.setTenantId(1);
agencyRequest.setTenantName("Test Tenant");
agencyRequest.setTimeZone("UTC");
String json = new Gson().toJson(agencyRequest);
System.out.println(json);
System.out.println(uri + "/" + ResourceConstants.JOB_CONFIG);
given().
accept(ContentType.JSON).
body(json).
post(new URI(uri + "/" + ResourceConstants.JOB_CONFIG)).
then().
assertThat().
statusCode(HttpStatus.OK_200);
}
如果我 运行 通过选择 post 方法和内容类型作为 json 对 Postman 进行相同的测试并使用正文,它给出的响应状态代码为 200。但是我的单元测试没有通过。在正文中,我曾尝试传递 json 字符串,如您之前所见,我也尝试传递 java 对象,但都失败了。
您需要在发送请求时定义请求的内容类型。考虑进行给定的更改
.contentType(ContentType.JSON)
尝试将这一行添加到代码的顶部:
.log().all()
.config(RestAssured.config().encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
.header()....
这个改动会奏效的,试试吧。
.header("Content-Type", "application/json").contentType(ContentType.JSON).accept(ContentType.JSON)