JsonSchema进行接口测试

何为JsonSchema

了解元数据的同学很容易理解JsonSchema和Json的关系。元数据是描述数据的数据,包括数据的属性、位置信息、获取方式等,而通常JsonSchema,主要描述Json数据的属性信息。
下面是一个简单的描述Person基本信息的Json数据

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 21
}

其对应的元数据为:

{
  "title": "Person", // Json描述的实体名称
  "type": "object", // Json实体类型
  "properties": {  // Json实体包括的属性信息
    "firstName": {  // 属性名
      "type": "string",  // 属性对应的Json类型
      "description": "The person's first name." // 属性描述
    },
    "lastName": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years which must be equal to or greater than zero.",
      "type": "integer",
      "minimum": 0  // 最小值
    }
  }
}

JsonShema的完整语法非常灵活,具体可以参照http://json-schema.org/understanding-json-schema/

有什么用

Json数据的应用范围非常广:接口数据参数及返回数据,传输数据,大数据存储数据等,在这些应用中JsonShema可以辅助:

  • 描述Json数据,方便理解数据内容,Json数据的释义文档完全可以选择JsonShema
  • 方便机器理解Json以实现测试自动化,例如对于数据进行校验,接口测试等

接口测试实例

JsonSchema进行接口测试Java实现
引入Jar包

<dependency>
     <groupId>org.everit.json</groupId>
     <artifactId>org.everit.json.schema</artifactId>
     <version>1.5.1</version>
     <scope>provided</scope>
 </dependency>

编写JsonUtil类进行校验

@Slf4j
public class JsonUtil {

    public static boolean validateJsonWithSchema(String schema, JSONObject jsonObject) {

        if (ObjectUtils.isEmpty(schema) || jsonObject == null) {
            Assert.fail("validateJsonWithSchema error, schema | jsonObject invalid");
            return false;
        }
        Schema jsonSchema;
        try {
            JSONObject json = new JSONObject(new JSONTokener(schema));
            jsonSchema = SchemaLoader.load(json);
        } catch (JSONException e) {
            log.error("validateJsonWithSchema fail", e);
            Assert.fail("validateJsonWithSchema fail, invalid jsonschema");
            return false;
        }

        try {
            jsonSchema.validate(jsonObject);
        } catch (ValidationException e) {
            log.error("validateJsonWithSchema fail: {}", e.getMessage());
            Assert.fail("validateJsonWithSchema fail");
            return false;
        }
        return true;
    }
}

为了详细的展示所有校验失败的地方,我们对ValidationException进行解析:

private static String getReason(ValidationException exception) {
        if (ObjectUtils.isEmpty(exception)) {
            return "";
        }
        String reason = "";
        List<ValidationException> exceptions = new ArrayList();
        exceptions.add(exception);
        int len = exceptions.size();
        int i = 0;
        while (i < len) {
            ValidationException e = exceptions.get(i);
            if (ObjectUtils.isEmpty(e.getCausingExceptions())) {
                reason += "\n" + e.getMessage();
                i += 1;
            } else {
                exceptions.addAll(e.getCausingExceptions());
                i += 1;
                len = exceptions.size();
            }
        }
        return reason;
    }

定义接口结果Schema
可以通过https://easy-json-schema.github.io/自动生成初版的JsonSchema

          {
           "type": "object",
           "required": ["result", "msg", "data"],
           "properties": {
            "result": {
             "type": "number",
             "minimum": 1,
             "maximun": 1
            },
            "msg": {
             "type": "string"
            },
            "data": {
             "type": "object",
             "required": ["dataCount", "list"],
             "properties": {
              "dataCount": {
               "type": "number",
               "minimum": 1
              },
              "list": {
               "type": "array",
               "minItems": 1,
               "items": {
                "type": "object",
                "required": ["userId", "reqId", "reqTime", "photoList"],
                "properties": {
                 "userId": {
                  "type": "string",
                  "minLength": 10
                 },
                 "reqId": {
                  "type": "string",
                  "minLength": 20
                 },
                 "reqTime": {
                  "type": "string",
                  "minLength": 13
                 },
                 "photoList": {
                  "type": "array",
                  "minItems": 6,
                  "items": {
                   "type": "object",
                   "required": ["itemId"],
                   "properties": {
                    "itemId": {
                     "type": "string",
                     "minLength": 10
                    },
                    "title": {
                     "type": "string"
                    }
                  }
                 }
               }
              }
             }
            }
           }
          }

运行结果
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值