如何将参数传递给 Rest-Assured

新手上路,请多包涵

在这种情况下有人可以帮助我吗:

当我调用此服务 http://restcountries.eu/rest/v1/ 时,我获得了几个国家的信息。

但是,当我想获取任何特定国家/地区的信息(例如芬兰)时,我调用 Web 服务作为 http://restcountries.eu/rest/v1/name/Finland 以获取与国家/地区相关的信息。

要使上述场景自动化,我如何在 Rest-Assured 中参数化国家/地区名称?我在下面尝试过,但对我没有帮助。

 RestAssured.given().
                    parameters("name","Finland").
            when().
                    get("http://restcountries.eu/rest/v1/").
            then().
                body("capital", containsString("Helsinki"));

原文由 Uday 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 539
1 个回答

正如文档所解释的那样:

REST Assured 将自动尝试根据 HTTP 方法确定哪种参数类型(即查询或表单参数)。在 GET 的情况下,将自动使用查询参数,在 POST 的情况下,将使用表单参数。

但在您的情况下,您似乎需要路径参数而不是查询参数。另请注意,获取国家/地区的通用 URL 是 https://restcountries.com/v2/name/{country} 其中 {country} 是国家/地区名称。

那么,传递路径参数的方式也有多种。

这里有几个例子

使用 pathParam() 的示例:

 // Here the key name 'country' must match the url parameter {country}
RestAssured.given()
        .pathParam("country", "Finland")
        .when()
            .get("https://restcountries.com/v2/name/{country}")
        .then()
            .body("capital", containsString("Helsinki"));

使用变量的示例:

 String cty = "Finland";

// Here the name of the variable (`cty`) have no relation with the URL parameter {country}
RestAssured.given()
        .when()
            .get("https://restcountries.com/v2/name/{country}", cty)
        .then()
            .body("capital", containsString("Helsinki"));

现在如果你需要调用不同的服务,你也可以像这样参数化“服务”:

 // Search by name
String val = "Finland";
String svc = "name";

RestAssured.given()
        .when()
            .get("https://restcountries.com/v2/{service}/{value}", svc, val)
        .then()
            .body("capital", containsString("Helsinki"));

// Search by ISO code (alpha)
val = "CH"
svc = "alpha"

RestAssured.given()
        .when()
            .get("https://restcountries.com/v2/{service}/{value}", svc, val)
        .then()
            .body("capital", containsString("Bern"));

// Search by phone intl code (callingcode)
val = "359"
svc = "callingcode"

RestAssured.given()
        .when()
            .get("https://restcountries.com/v2/{service}/{value}", svc, val)
        .then()
            .body("capital", containsString("Sofia"));

之后,您还可以轻松使用 JUnit @RunWith(Parameterized.class) 为单元测试提供参数“svc”和“value”。

原文由 рüффп 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题