我正在使用MockRestServiceServer对我的休息终点进行单元测试。当我使用
时,我在工作状态下进行了一次单元测试mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST))
.andRespond(withSuccess(response, MediaType.TEXT_PLAIN));
但是当我使用
时,同样失败了mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST))
.andRespond(withBadRequest().body("test").contentType( MediaType.TEXT_PLAIN));
这是完整的代码
@Test
public void testPost() {
ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory();
mockServer = MockRestServiceServer.createServer(restTemplate);
try {
WebTarget target = getRootTarget("/test").path("");
String payLoad = ReadFile("src/test/resources/SamplePayload.html");
String response = ReadFile("src/test/resources/SampleResponse.txt");
Assert.assertNotNull(payLoad);
Assert.assertNotNull(response);
final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(payLoad, "text/plain");
mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST))
.andRespond(withSuccess(response, MediaType.TEXT_PLAIN));
final Response mockResponse = target.request().post(entity);
mockServer.verify();
Assert.assertNotNull("Response must not be null", mockResponse.getEntity());
Assert.assertEquals("Response does not have expected response code", 200, mockResponse.getStatus());
} finally {
restTemplate.setRequestFactory(originalRequestFactory);
}
}
@Test
public void testPostWithEmptyBody() {
ClientHttpRequestFactory originalRequestFactory = restTemplate.getRequestFactory();
mockServer = MockRestServiceServer.createServer(restTemplate);
try{
WebTarget target = getRootTarget("/test").path("");
String entityBody = new String();
final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");
mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST))
.andRespond(withBadRequest().body("test").contentType( MediaType.TEXT_PLAIN));
final Response response = target.request().post(entity);
mockServer.verify();
Assert.assertNotNull("Response must not be null", response.getEntity());
Assert.assertEquals("Response does not have expected response code", 400, response.getStatus());
}finally {
restTemplate.setRequestFactory(originalRequestFactory);
}
}
target.request()。post()是只调用
的函数resttemplate.postForEntity
在第二个测试案例中,我期待状态代码为400,但我得到500.任何建议?
答案 0 :(得分:0)
也许你的RestTemplate不包含正确的MessageConvertor来解析
MediaType.TEXT_PLAIN
。