Ich verwende MockRestServiceServer für die Einheit, die meinen Ruheendpunkt testet. Ich habe einen Komponententest in einwandfreiem Zustand, wenn ichFehler im Komponententest mit MockRestServiceServer
mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST))
.andRespond(withSuccess(response, MediaType.TEXT_PLAIN));
verwenden aber gleiche schlägt fehl, wenn ich
mockServer.expect(requestTo(containsString(ROOT_RESOURCE_PATH))).andExpect(method(HttpMethod.POST))
.andRespond(withBadRequest().body("test").contentType(MediaType.TEXT_PLAIN));
Hier vollständige Code ist
@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 () ist Funciton, die gerade ruft
resttemplate.postForEntity
Im zweiten Testfall erwarte ich einen Statuscode von 400, dafür bekomme ich 500.Andere Vorschläge?