Rest Assured Framework 完成 JSON 响应匹配

Rest Assured Framework complete JSON response matching

我正在使用 Rest Assured Framework 进行 API 测试(使用 Java)。 在第 (1) 行,我预计会出现错误,因为预期 JSON 响应和实际 JSON 响应不匹配 但是我的代码却成功执行了。 如果我在下面的代码中做错了什么,有人可以告诉我吗?

     public void test123() {
            try {
                //Read the Curl Request Input file
                String json = input.readFromTextFile(
                        System.getProperty("user.dir") + "\src\test\resources\inputFile\CurlDataFile.txt");
                json = json.replaceAll(" ", "");            
                RestAssured.baseURI = "My URL";
                given().
                    contentType("application/json").
                    body(json).
                when().
                    post("").
                then().
assertThat().body(matchesJsonSchemaInClasspath("testCurlOuput1.json"));  (1)
            } catch (IOException e) {
                e.printStackTrace();
            }catch(JsonSchemaValidationException e){
                e.printStackTrace();
            }
        }

您正在捕获所有异常。当您的 assertThat(..) 失败时,它会抛出异常。在 e.printStackTrace(); 上放置一个断点; 运行 在 DEBUG 模式下并检查你的 AssertionException/Error 没有被捕获。

无需捕获异常,只需将所有已检查的异常添加到您的测试签名中即可。如果异常未被捕获,它将无法通过测试。或者,但我认为不太喜欢,通过放置 fail(); 来解决。在 catch 块中。

最后我选择了不同的库,即 jayway.restassured 库,然后是 JSON Assert 库 (org.skyscreamer.jsonassert.JSONAssert),它将比较实际和预期的响应。

public void test123() {         
String postData = input.readFromTextFile(System.getProperty("user.dir") + "\src\test\resources\inputFile\CurlDataFile.txt");
        RestAssured.baseURI = "MY URL";
Response r = (Response)given().contentType("application/json").body(postData).when().post("");
            String responseBody = r.getBody().asString();           
            String curlResponse = //I am providing expected Curl response here          
       //JSON Assertion for matching Expected and Actual response
            JSONAssert.assertEquals(curlResponse, responseBody, false);
        }

有时我们可能希望避免比较来自 JSON 的特定字段,例如一些动态生成的 ID 字段,我们可以使用 JSON comparator

我是 JSONAssert 的粉丝,因为它可以轻松比较完整的 JSON。

只需使用 .extract().response().getBody().asString() 即可得到答案的字符串表示形式。

完整示例:

@Test
public void getReturnsExpectedDataForMailExampleCom() throws JSONException {
    String response = get("/users/mail@example.com")
        .then()
        .statusCode(200)
        .extract().response().getBody().asString();
    JSONAssert.assertEquals(
        "{\"email\":\"mail@example.com\",\"locale\":\"de-DE\"}",
        response,
        false);
}

Update 缺点是如果断言失败,完整的JSON不会输出到stdout。

这与 REST-assured 没有直接关系,但我建议您看一下 Karate,因为 IMO 它可能正是您要找的东西。

空手道的核心功能之一是您可以一步完成 等同 匹配 JSON 负载。

而且您可以轻松地从文件中使用 JSON,这鼓励在多个测试中重复使用负载。