企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 40.3.6 自动配置的JSON测试 你可以使用`@JsonTest`测试对象JSON序列化和反序列化是否工作正常,该注解将自动配置Jackson `ObjectMapper`,`@JsonComponent`和Jackson `Modules`。如果碰巧使用gson代替Jackson,该注解将配置`Gson`。使用`@AutoConfigureJsonTesters`可以配置auto-configuration的元素。 Spring Boot提供基于AssertJ的帮助类(helpers),可用来配合JSONassert和JsonPath libraries检测JSON是否为期望的,`JacksonHelper`,`GsonHelper`,`BasicJsonTester`分别用于Jackson,Gson,Strings。当使用`@JsonTest`时,你可以在测试类中`@Autowired`任何helper字段: ```java import org.junit.*; import org.junit.runner.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.autoconfigure.json.*; import org.springframework.boot.test.context.*; import org.springframework.boot.test.json.*; import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*; @RunWith(SpringRunner.class) @JsonTest public class MyJsonTests { @Autowired private JacksonTester<VehicleDetails> json; @Test public void testSerialize() throws Exception { VehicleDetails details = new VehicleDetails("Honda", "Civic"); // Assert against a `.json` file in the same package as the test assertThat(this.json.write(details)).isEqualToJson("expected.json"); // Or use JSON path based assertions assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") .isEqualTo("Honda"); } @Test public void testDeserialize() throws Exception { String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}"; assertThat(this.json.parse(content)) .isEqualTo(new VehicleDetails("Ford", "Focus")); assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford"); } } ``` **注** JSON帮助类可用于标准单元测试类,如果没有使用`@JsonTest`,你需要在`@Before`方法中调用帮助类的`initFields`方法。 在[附录](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@JsonTest`开启的自动配置列表。