gpt4 book ai didi

java - 如何通过 RestAssured 重用常见断言

转载 作者:行者123 更新时间:2023-12-01 21:18:37 24 4
gpt4 key购买 nike

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

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

}

关于java - 如何通过 RestAssured 重用常见断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39496570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com