美文网首页
JsonUnit 断言框架用法总结

JsonUnit 断言框架用法总结

作者: 林万程 | 来源:发表于2020-02-17 17:39 被阅读0次

JsonUnit 断言 JSON

<dependency>
    <groupId>net.javacrumbs.json-unit</groupId>
    <artifactId>json-unit-assertj</artifactId>
    <version>2.13.0</version>
    <scope>test</scope>
</dependency>
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.json;

assertThatJson("{\"a\":1, \"b\":2}").isEqualTo("{b:2, a:1}");
assertThatJson(jacksonObject).isEqualTo("{\n\"test\": 1\n}");
assertThatJson("{\"a\":1}").isObject()
    .containsEntry("a", BigDecimal.valueOf(1));
assertThatJson("{\"test\":1.00001}").node("test")
    .withTolerance(0.001).isEqualTo(1);

数组

assertThatJson("{\"a\":[{\"b\": 1}, {\"c\": 1}, {\"d\": 1}]}")
    .node("a").isArray()
    .contains(json("{\"c\": 1}"));

assertThatJson("{\"root\":{\"test\":[1,2,3]}}")
    .node("root.test[-1]").isEqualTo(3);

类型

assertThatJson("{\"test\":\"value\"}")
    .isEqualTo("{test:'${json-unit.any-string}'}");

assertThatJson("{\"test\":true}")
    .isEqualTo("{\"test\":\"${json-unit.any-boolean}\"}");
    
assertThatJson("{\"test\":1.1}")
    .isEqualTo("{\"test\":\"${json-unit.any-number}\"}");

忽略

assertThatJson("{\n\"test\": {\"object\" : {\"another\" : 1}}}")
    .isEqualTo("{\"test\":\"${json-unit.ignore}\"}");

assertThatJson("{\"root\":{\"test\":1, \"ignored\": null}}")
    .isEqualTo("{\"root\":{\"test\":1, \"ignored\": \"${json-unit.ignore-element}\"}}");

assertThatJson("{\"root\":{\"test\":1, \"ignored\": 1}}")
    .whenIgnoringPaths("root.ignored"))
    .isEqualTo("{\"root\":{\"test\":1}}");

与或非

assertThatJson("{\"test\":{\"a\":1, \"b\":2, \"c\":3}}").and(
    a -> a.node("test.a").isEqualTo(1),
    a -> a.node("test.b").isEqualTo(2)
);

正则

assertThatJson("{\"test\": \"ABCD\"}")
    .isEqualTo("{\"test\": \"${json-unit.regex}[A-Z]+\"}");

自定义

assertThatJson("{\"test\":-1}")
    .withConfiguration(c -> c.withMatcher("positive", greaterThan(valueOf(0))))
    .isEqualTo("{\"test\": \"${json-unit.matches:positive}\"}");

配置

assertThatJson("{\"a\":[{\"b\": 1}, {\"c\": 1}, {\"d\": 1}]}")
    .when(TREATING_NULL_AS_ABSENT) // 具有空值的字段等效于不存在的字段
    .when(IGNORING_ARRAY_ORDER) // 忽略数组中的顺序
    .when(IGNORING_EXTRA_ARRAY_ITEMS) // 忽略意外的数组项
    .when(IGNORING_EXTRA_FIELDS) // 忽略比较值中的额外字段
    .when(IGNORE_VALUES) // 忽略值并仅比较类型
    .node("a").isArray()
    .isEqualTo(json("[{\"c\": 1}, {\"b\": 1} ,{\"d\": 1}]"));

JsonPath

assertThatJson(json)
    .inPath("$.store.book").isArray()
    .contains(json(
        "            {\n" +
            "                \"category\": \"reference\",\n" +
            "                \"author\": \"Nigel Rees\",\n" +
            "                \"title\": \"Sayings of the Century\",\n" +
            "                \"price\": 8.96\n" +
            "            }"
    ));

相关文章

网友评论

      本文标题:JsonUnit 断言框架用法总结

      本文链接:https://www.haomeiwen.com/subject/qvcifhtx.html