这是我的api我使用了Jersey和spring boots.api工作正常,产生正确的响应,我想编写单元测试用例来检查api使用Junit。
@POST
@Path("/trip/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createTrip(Trip pObjTrip, @HeaderParam("Auth-Token") String pAuthToken) {
Response lRetVal = new Response();
appLog.info(String.format("Creating a trip with [%s]", pObjTrip));
try {
User lObjUser = validateUser(pAuthToken, lRetVal);
if(lObjUser == null) {
} else if (StringUtils.isEmpty(pObjTrip.getTripName())) {
lRetVal.setResult(ResponseIds.API_RESULT_INSUFFICIENT_INFO);
lRetVal.setMessage("All information are not provided");
} else {
lObjUser.setEnabled(true);
pObjTrip.setCreatedBy(lObjUser);
pObjTrip.setCreateTime(Calendar.getInstance());
pObjTrip.setTripStatus(Trip.TRIP_STATUS_CREATED);
m_cObjTripService.saveAndFlush(pObjTrip);
lRetVal.setResult(ResponseIds.API_RESULT_SUCCESS);
lRetVal.setValue(pObjTrip);
}
} catch (Exception ex) {
appLog.warn(ex.toString(), ex);
}
return lRetVal;
}
我在搜索后编写了测试用例但是(http://localhost:8080/api/trphpr/trip/create)得到了400个错误的请求。
@After(value = "http://localhost:8080/api/trphpr/trip/create")
public void testCreateTripApi() throws IOException{
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(2);
map.add("tripNme", "test trip");
org.springframework.http.HttpHeaders lhttpheader = new org.springframework.http.HttpHeaders();
lhttpheader.add("Auth-Token", "7f8b655a007dda8f93a77fcb44de3298efb67615a5585b2fdc6c95b4cc2c4a52282deae6119a2fd6c3f9b4e3723e3d1cb221376ed36d978f0ff31b585d8e70f4");
lhttpheader.setContentType(MediaType.APPLICATION_JSON);
List<HttpMessageConverter<?>> msgConverters = restTemplate.getMessageConverters();
msgConverters.add(new MappingJackson2HttpMessageConverter());
restTemplate.setMessageConverters(msgConverters);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, lhttpheader);
Response apiResponse = (Response) restTemplate.postForObject("http://localhost:8080/api/trphpr/trip/create", request, Response.class);
assertNotNull(apiResponse);
//Asserting the response of the API.
String message = apiResponse.getMessage();
Trip ltrip = (Trip)apiResponse.getValue();
assertEquals("trip created successfully", message);
assertEquals("trip test", ltrip.getTripName());
}
}