有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无JSON方案响应的java放心JSON验证

我想检查JSON响应是否正确,至少是有效的,并且无法找到正确的方法来使用REST Assured实现这一点

我在REST Assured examples中读了很多关于matchesJsonSchemaInClasspath的书,但我还不想写整个JSON模式

get("/products").
    then().
    assertThat().
    body(matchesJsonSchemaInClasspath("products-schema.json"));

如果不添加该检查,任何格式错误的JSON检查都会被通过——因此即使JSON无效,我也可以检查字段值,或者,例如数组大小

import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.get;
import static org.hamcrest.core.Is.is;


public class RestEndpointTest{
    @Test
    public void basic_rest_check() {
        get("/my_endpoint").
            then().
            assertThat().
            body("size()", is(2)).
            statusCode(200);
    }
}

即使是响应,测试也通过了:

[{},{}]MALFORMED

共 (1) 个答案

  1. # 1 楼答案

    现在,这是微不足道的,但我发现,只有在几天之后,我才提出我的问题。因此,解决方案是使用matchesJsonSchema代替matchesJsonSchemaInClasspath

    import org.junit.jupiter.api.Test;
    
    import static io.restassured.RestAssured.get;
    import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
    
    public class RestEndpointTest{
        @Test
        public void basic_rest_check() {
            get("/my_endpoint").
                then().
                assertThat().
                body(matchesJsonSchema("{}")).
                statusCode(200);
        }
    }
    

    说明:关于http://json-schema.org/

    The most basic schema is a blank JSON object, which constrains nothing, allows anything, and describes nothing:

    {}

    另外还有一个选项,可以使用该内容创建文件{},并通过matchesJsonSchemaInClasspath加载该文件