Har*_*ana 6 java rest junit json rest-assured
我正在使用junit4放心.在我的测试方法中,我在mongodb中创建一个对象,当我运行测试时,它也成功地持久存在.但我需要存储创建的ID,所以我尝试获取响应正文.但这response.getBody().asString()是空的.
@Test
public void testA() throws JSONException {
Map<String,Object> createVideoAssignmentParm = new HashMap<String,Object>();
createVideoAssignmentParm.put("test1", "123");
Response response = expect().statusCode(201).when().given().contentType("application/json;charset=UTF-8")
.headers(createVideoAssignmentParm).body(assignment).post("videoAssignments");
JSONObject jsonObject = new JSONObject(response.getBody().asString());
id= (String)jsonObject.getString("assignmentId");
}
Run Code Online (Sandbox Code Playgroud)
当我从外部调用其余端点时,它会返回响应主体以及相关字段,因此其余API没有问题.
如果没有上述问题的答案那么你们将如何使用放心测试带有返回体的帖子,以便我可以尝试这种方式.
我的控制器方法看起来像,
@RequestMapping(value = "/videoAssignment", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@ResponseBody
public HttpEntity<VideoAssignment> createVideoAssingnment(
//@ApiParam are there..){
//other methods
return new ResponseEntity<>(va, HttpStatus.CREATED);
}
Run Code Online (Sandbox Code Playgroud)
我们使用不同的 wat 来调用 RestAssured 的服务。但是,如果您得到一个空字符串,您可以使用.peek().
您可以使用此测试:
@Test
public void testStatus()
{
String response =
given()
.contentType("application/json")
.body(assignment)
.when()
.post("videoAssignments")
.peek() // Use peek() to print the ouput
.then()
.statusCode(201) // check http status code
.body("assignmentId", equalTo("584")) // whatever id you want
.extract()
.asString();
assertNotNull(response);
}
Run Code Online (Sandbox Code Playgroud)