英文:
Add Condition to Rest Assured
问题
我想要在Rest Assured中添加一个条件。例如,如果我有输入1,请求应该检查条件1,但如果我没有输入1,则不应该检查条件1。当然,我可以在请求之外使用if语句,然后不添加检查,但我有几种类似的情况,这会产生很多不必要的代码。有没有办法使用内联if语句来节省代码?
response =
given().
spec(spec).
body(data).
when().
post("/test").
then().
assertThat().
statusCode(201).
body("id", condition1 ? equalTo(1) : anything()).
extract().
response();
英文:
I want to add a condition to Rest Assured. For example, if I have input 1, the request should be checked for condition 1, but if I do not have input 1, condition 1 should not be checked. Of course I could do the if outside the request and just not add the check, but I have several cases like this this is a lot of unnecessary code. Is there any way I can save code using an inline if?
if (condition1){
response =
given().
spec(spec).
body(data).
when().
post("/test").
then().
assertThat().
statusCode(201).
body("id", 1).
extract().
response();
} else {
response =
given().
spec(spec).
body(data).
when().
post("/test").
then().
assertThat().
statusCode(201).
//DONT DO THE CHECK
extract().
response();
}
Is there a way to do that in one line? Something like this:
response =
given().
spec(spec).
body(data).
when().
post("/test").
then().
assertThat().
statusCode(201).
if condition do this body("id", 1) otherwise dont do anything
extract().
response();
答案1
得分: 1
以下是翻译好的部分:
你可以尝试类似以下的代码:
ValidatableResponse validatableResponse =
given()
.spec(spec)
.body(data)
.when()
.post(endpoint)
.then()
.spec(responseSpec)
.assertThat();
if (condition) {
validatableResponse.body("id", 1)
}
Response response = validatableResponse.extract().response();
英文:
You can try something like this:
ValidatableResponse validatableResponse =
given()
.spec(spec)
.body(data)
.when()
.post(endpoint)
.then()
.spec(responseSpec)
.assertThat();
if (condition) {
validatableResponse.body("id", 1)
}
Response response = validatableResponse.extract().response();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论