接口自动化测试之旅--JsonSchema

来源:互联网 发布:设备吞吐量测试软件 编辑:程序博客网 时间:2024/06/16 12:41

接口自动化测试之旅–JsonSchema

针对接口测试结果校验,现在除了对返回值一一的校验以外,由于一一校验的不完整性,由此增加了JsonSchema的校验方式,可以全局方式校验 JSON结构

在线 JSONSchema 生成地址:http://JSONschema.net/#/home

JAVA工程增加jar包

        <dependency>            <groupId>com.github.fge</groupId>            <artifactId>json-schema-validator</artifactId>            <version>2.2.6</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-core</artifactId>            <version>2.3.0</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>2.3.0</version>        </dependency>

封装成方法

/**     * JSON Schema 比对     * 生成格式文件地址: http://JSONschema.net/#/home     * @param data 本地源JOSNS数据     * @param schema JSON Schema     * @return     */    public static Boolean validationJSONSchema(String data,String schema){        ProcessingReport resultReport = null;        try{            //源jsonNode            JsonNode dataValue = JsonLoader.fromString(data);            log.info("源JSONSchema:" + dataValue.toString());            //目标jsonNode            JsonNode schemaValue = JsonLoader.fromString(schema);            log.info("目标JSONSchema:" + schemaValue.toString());//            ProcessingReport resultReport = factory.getValidator().validateUnchecked(sourceJSONNode,targetJSONNode);            resultReport = factory.byDefault().getValidator().validateUnchecked(schemaValue,dataValue);            if(resultReport.isSuccess()){                log.info("JSON Schema匹配 通过");                return true;            }        }catch (Exception e){            e.printStackTrace();            log.info("JSON Schema匹配 失败");        }        log.info("JSON Schema匹配 失败");        Iterator<ProcessingMessage> it = resultReport.iterator();        while (it.hasNext()) {            log.info(it.next());        }        return false;    }

测试验证:

/**     * 测试查询章节详情     */    @Test    public void testGetTrainingChapter() throws IOException {        String chapterId = "189";        String userId = "10980500000";        int pageIndex = 1;        int pageSize = 20;        JSONObject result = JSONObject.fromObject(sampleApi.getTrainingChapter(chapterId,userId,pageIndex,pageSize));        String dataValue = fileMethodUtils.readTxtViaResources("JSONSchema/SampleApi/getTrainingChapter/200.txt");        String schemaValue = result.toString();        //JSON格式比对        Assert.assertTrue("JOSN格式比对结果:",validationJSONSchema(dataValue,schemaValue));    }
0 0