我有用于Spring云合同测试的生产者和消费者项目。我有基于成功方案的测试用例和基于错误方案的测试用例,它们在消费者方面都可以正常工作。但是,对于错误情形,它没有返回自定义的错误响应并在用户端通过测试用例,而是在用户项目中引发了异常。生产者项目两个场景生成的测试用例都很好。
生产者方常规脚本: 如您所见,我在正文中为accountId传递了无效的String值,而不是Long值。
Contract.make {
request {
method PUT()
urlPath("/api/v1/a")
headers {
contentType('application/json')
}
body("{\"accountId\": \"11332382Adg\" ,\"caseNumber\":\"CIS0005468\",\"representmentStartDate\":\"20181212\"}")
}
response {
status 400
headers {
contentType('application/json')
}
body([
"errorDescription": "invalid request or invalid date format"
])
}
}
以下通过目标生成的测试用例。 生成方的测试用例(这是成功并通过)
public class Rap extends SRAP {
@Test
public void validate InvalidateRequest() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"accountId\":\"11332382Adg\",\"caseNumber\":\"CIS0005468\",\"representmentStartDate\":\"20181212\"}");
// when:
ResponseOptions response = given().spec(request)
.put("/api/v1/a");
// then:
assertThat(response.statusCode()).isEqualTo(400);
assertThat(response.header("Content-Type")).matches("application/json.*");
// and:
DocumentContext parsedJson = JsonPath.parse(response.getBody().asString());
assertThatJson(parsedJson).field("['errorDescription']").isEqualTo("invalid request or invalid date format");
}
}
Test的超类,它由target中生成的子类扩展。该类具有我在测试用例中使用的错误响应,在该情况下,每当调用一个异常时,我都会调用buildErrorResponse()方法,该方法将返回自定义的错误响应。
`class SRAP{
public void setup() {
StandaloneMockMvcBuilder standaloneMockMvcBuilder = MockMvcBuilders.standaloneSetup(findCaseController, ApiController, controllerExceptionAdvice);
RestAssuredMockMvc.standaloneSetup(standaloneMockMvcBuilder);
when(controllerExceptionAdvice.handleHttpMessageNotReadable(any(), any(), any(), any()))
.thenReturn(
new ResponseEntity<>(
buildErrorResponse(),
HttpStatus.BAD_REQUEST
)
);
when(controllerExceptionAdvice.handleMethodArgumentTypeMismatchException(any(), any()))
.thenReturn(
new ResponseEntity<>(
buildErrorResponse(),
HttpStatus.BAD_REQUEST
)
);
private ErrorResponse buildErrorResponse() {
ErrorResponse errorResponse = ErrorResponse.builder().build();
errorResponse.setErrorDescription("invalid request or invalid date format");
return errorResponse;
}
}
消费者方面的成功测试案例:
@Test
public void should_update_case_success() throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json");
ResponseEntity<String> response = restTemplate.exchange(
"http://localhost:8083/api/v1/a",
HttpMethod.PUT,
new HttpEntity<>("{\"accountId\":\"1112321\",\"caseNumber\":\"CIS1233\",\"representmentStartDate\":\"20181212\"}", httpHeaders), String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(200);
}
消费者端测试用例失败:我给accountId赋予了无效值,因为它失败了,并给了我一个自定义的错误响应
@Test
public void case_error() throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json");
ResponseEntity<String> response = restTemplate.exchange(
"http://localhost:8083/api/v1/a",
HttpMethod.PUT,
new HttpEntity<>("{\"accountId\":\"11332382Adg\",\"caseNumber\":\"CIS0005468\",\"representmentStartDate\":\"20181212\"}", httpHeaders), String.class);
BDDAssertions.then(response.getStatusCodeValue()).isEqualTo(400);
System.out.println("response " + response.getBody());
BDDAssertions.then(response.getBody().equals("{\"errorDescription\":\"invalid request or invalid date format\"}"));
即使在日志中,我也得到了与Stubs-jar相匹配的响应,但是为什么测试用例失败了?:
Matched response definition:
{
"status" : 400,
"body" : "{\"errorDescription\":\"invalid request or invalid date format\"}",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template" ]
}
Response:
HTTP/1.1 400
Content-Type: [application/json]`
仅在我通过的情况下,消费者方的错误测试用例才通过,但是我应该获得自定义的错误响应
@Test(expected=HttpClientErrorException.class)
预期结果:应返回定制的错误正文并通过测试用例。
{ errorDescription: invalid request or invalid date format }
实际结果:org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request