> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/43.-testing/43.3-testing-spring-boot-applications/43.3.7-auto-configured-json-tests.md).

# 43.3.7 自动配置的JSON测试

你可以使用`@JsonTest`测试对象JSON序列化和反序列化是否工作正常。该注解将自动配置支持JSON映射器的可用库。可以是下列库里的一种：

* `Jackson ObjectMapper`，任何`@JsonComponent` bean，任何Jackson `模块`
* `Gson`
* `Jsonb`

使用`@AutoConfigureJsonTesters`可以配置auto-configuration的元素。

Spring Boot提供基于AssertJ的帮助类（helpers），可用来配合JSONassert和JsonPath库检测JSON是否和期望的一样。`JacksonTester`、`GsonTester`、`JsonbTester`和`BasicJsonTester`分别用于Jackson、Gson、Jsonb、Strings。当使用`@JsonTest`时，你可以在测试类中`@Autowired`任何helper字段。下面的例子展示了一个用于Jackson的测试类：

```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`方法。

在[附录](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@JsonTest`开启的自动配置列表。
