Java SpringBoot2测试json序列化

Java SpringBoot2测试json序列化,java,unit-testing,spring-boot,jackson,Java,Unit Testing,Spring Boot,Jackson,我有以下测试,它的工作正常。然而在我看来这有点过分了。(也需要一段时间)启动spring的完整实例以测试一些json序列化 @RunWith(SpringRunner.class) @SpringBootTest public class WirelessSerializationTest { @Autowired ObjectMapper objectMapper; @Test public void testDateSerialization() throws IOExc

我有以下测试,它的工作正常。然而在我看来这有点过分了。(也需要一段时间)启动spring的完整实例以测试一些json序列化

@RunWith(SpringRunner.class)
@SpringBootTest
public class WirelessSerializationTest {

  @Autowired
  ObjectMapper objectMapper;

  @Test
  public void testDateSerialization() throws IOException {

    Resource resource = new ClassPathResource("subscription.json");
    File file = resource.getFile();

    CustomerSubscriptionDto customerSubscriptionDto = objectMapper.readValue(file, CustomerSubscriptionDto.class);
    LocalDateTime actualResult = customerSubscriptionDto.getEarliestExpiryDate();

    LocalDate expectedDate = LocalDate.of(2018, 10, 13);
    LocalTime expectedTime = LocalTime.of( 10, 18, 48);
    LocalDateTime expectedResult = LocalDateTime.of(expectedDate,expectedTime);
    Assert.assertEquals("serialised date ok", expectedResult, actualResult);

    String jsonOutput = objectMapper.writeValueAsString(customerSubscriptionDto);
    String expectedExpiryDate = "\"earliestExpiryDate\":\"2018-10-13T10:18:48Z\"";

  }

}
现在我可以通过删除SpringRunner来简化它。但是我没有在这里加载jackson配置的弹簧

public class WirelessSerializationTest {

  //@Autowired
  ObjectMapper objectMapper = new ObjectMapper();

所以我的问题是。我可以在测试中测试并加载Springs ObjectMapper实例,而不需要加载所有Spring up吗?

使用
@JsonTest
而不是
@SpringBootTest


它将加载与测试相关的上下文片段。

是的,作为测试的一部分初始化它。如果不需要加载spring上下文,则不需要完整的
SpringRunner
内容

ObjectMapper
不是Spring的一部分,它是Jackson的一部分,您可以在没有Spring上下文的情况下实例化它。如果在应用程序中为
ObjectMapper
使用任何特殊配置,请务必小心,以确保复制它

例如(这里我配置了两个选项,仅用于说明):

您还可以创建Spring的
MockMvc
来模拟对它的HTTP请求并触发控制器,并将
ObjectMapper
传递给它,仍然不必使用重型
SpringRunner

private ObjectMapper objectMapper = Jackson2ObjectMapperBuilder().build()                                      
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    .setSerializationInclusion(Include.NON_ABSENT);