如何使用RestAssured重用常见断言

时间:2016-09-14 17:40:10

标签: java dry

我有一些使用RestAssured的java测试。对于许多测试,given()和when()参数不同,但then()部分是相同的,由多个assertThat()语句组成。如何将then()块移动到我可以反复使用的新方法?

docker volume

1 个答案:

答案 0 :(得分:3)

您可以使用ResponseSpecification创建一组可用于多个响应的断言。这与你提出的问题有点不同,但可以照顾你的需要。此示例还使用RequestSpecification设置可在多个Rest调用中使用的公共请求设置。这尚未经过全面测试,但您的代码看起来像这样:

public static RequestSpecBuilder reqBuilder;
public static RequestSpecification requestSpec;  //set of parameters that will be used on multiple requests
public static ResponseSpecBuilder resBuilder;
public static ResponseSpecification responseSpec; //set of assertions that will be tested on multiple responses

@BeforeClass
public static void setupRequest()
{
    reqBuilder = new RequestSpecBuilder();
    //Here are all the common settings that will be used on the requests
    reqBuilder.setContentType("application/json");
    requestSpec = reqBuilder.build();
} 

@BeforeClass
public static void setupExpectedResponse()
{
    resBuilder = new ResponseSpecBuilder();
    resBuilder.expectStatusCode(HttpStatus.SC_OK)
    .body("pollInterval", equalTo(defaultPollInterval))
    .body("notifications", hasSize(0));
    responseSpec = resBuilder.build();
}  


@Test 
public void restAssuredTestUsingSpecification() {
    //Setup the call to get the bearer token
    Response accessResponse = given()
        .spec(requestSpec)
    .when()
        .get("inapp/messages.json")
    .then()
        //Verify that we got the results we expected
        .spec(responseSpec);

}