JsonUnit 断言框架用法总结

2020-02-24 12:36:12 浏览数 (2)

JsonUnit 断言 JSON

代码语言:javascript复制
<dependency>
    <groupId>net.javacrumbs.json-unit</groupId>
    <artifactId>json-unit-assertj</artifactId>
    <version>2.13.0</version>
    <scope>test</scope>
</dependency>
代码语言:javascript复制
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": 1n}");
assertThatJson("{"a":1}").isObject()
    .containsEntry("a", BigDecimal.valueOf(1));
assertThatJson("{"test":1.00001}").node("test")
    .withTolerance(0.001).isEqualTo(1);

数组

代码语言:javascript复制
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);

类型

代码语言:javascript复制
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}"}");

忽略

代码语言:javascript复制
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}}");

与或非

代码语言:javascript复制
assertThatJson("{"test":{"a":1, "b":2, "c":3}}").and(
    a -> a.node("test.a").isEqualTo(1),
    a -> a.node("test.b").isEqualTo(2)
);

正则

代码语言:javascript复制
assertThatJson("{"test": "ABCD"}")
    .isEqualTo("{"test": "${json-unit.regex}[A-Z] "}");

自定义

代码语言:javascript复制
assertThatJson("{"test":-1}")
    .withConfiguration(c -> c.withMatcher("positive", greaterThan(valueOf(0))))
    .isEqualTo("{"test": "${json-unit.matches:positive}"}");

配置

代码语言:javascript复制
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

代码语言:javascript复制
assertThatJson(json)
    .inPath("$.store.book").isArray()
    .contains(json(
        "            {n"  
            "                "category": "reference",n"  
            "                "author": "Nigel Rees",n"  
            "                "title": "Sayings of the Century",n"  
            "                "price": 8.96n"  
            "            }"
    ));

0 人点赞