Spring Boot提供基于AssertJ的帮助类(helpers),可用来配合JSONassert和JsonPath库检测JSON是否和期望的一样。JacksonTester、GsonTester、JsonbTester和BasicJsonTester分别用于Jackson、Gson、Jsonb、Strings。当使用@JsonTest时,你可以在测试类中@Autowired任何helper字段。下面的例子展示了一个用于Jackson的测试类:
importorg.junit.*;importorg.junit.runner.*;importorg.springframework.beans.factory.annotation.*;importorg.springframework.boot.test.autoconfigure.json.*;importorg.springframework.boot.test.context.*;importorg.springframework.boot.test.json.*;importorg.springframework.test.context.junit4.*;importstaticorg.assertj.core.api.Assertions.*;@RunWith(SpringRunner.class)@JsonTestpublicclassMyJsonTests { @AutowiredprivateJacksonTester<VehicleDetails> json; @TestpublicvoidtestSerialize() throwsException {VehicleDetails details =newVehicleDetails("Honda","Civic");// Assert against a `.json` file in the same package as the testassertThat(this.json.write(details)).isEqualToJson("expected.json");// Or use JSON path based assertionsassertThat(this.json.write(details)).hasJsonPathStringValue("@.make");assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make").isEqualTo("Honda"); } @TestpublicvoidtestDeserialize() throwsException {String content ="{\"make\":\"Ford\",\"model\":\"Focus\"}";assertThat(this.json.parse(content)).isEqualTo(newVehicleDetails("Ford","Focus"));assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); }}