简体   繁体   中英

How to reuse common asserts with RestAssured

I've got some java tests that use RestAssured. For many of the tests, the given() and when() parameters are different, but the then() section is the same and consists of multiple assertThat() statements. How do I move the then() block to a new method that I can use over and over?

@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));
}

You can use ResponseSpecification to create a set of assertions that can be used on multiple responses. This is a bit different than how you have the question phrased, but could take care of your need. This example also uses a RequestSpecification to setup common request settings that can be used across multiple Rest calls. This is not fully tested, but your code would look something like this:

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM