如何使用 RestAssured 重用通用断言

How to reuse common asserts with RestAssured

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

@Test
public void test_inAppMsgEmptyResponse() {
    given().
            contentType("application/json").
    when().
            get("inapp/messages.json").
    then().assertThat().
            statusCode(HttpStatus.SC_OK).
            assertThat().
            body("pollInterval", equalTo(defaultPollInterval)).
            assertThat().
            body("notifications", hasSize(0));
}

您可以使用 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);

}