猿问

Spring boot 2 测试json序列化

我有以下测试,它工作正常。然而在我看来它有点矫枉过正。(也需要一段时间)调出一个完整的 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 来简化它。但是我没有在这里加载弹簧杰克逊配置。


public class WirelessSerializationTest {


  //@Autowired

  ObjectMapper objectMapper = new ObjectMapper();

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


白衣染霜花
浏览 180回答 2
2回答

叮当猫咪

使用@JsonTest代替@SpringBootTesthttps://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/json/JsonTest.htmlhttps://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-json-tests它将加载与 jackson 序列化相关的上下文片段,以进行更多测试。

交互式爱情

是的,只需将其初始化为测试的一部分。SpringRunner如果您不需要加载 spring 上下文,则不需要完整内容。ObjectMapper不是 Spring 的一部分,它是 Jackson 的一部分,您可以在没有 Spring 上下文的情况下实例化它就好了。如果您在应用程序中使用了任何特殊配置,请务必小心ObjectMapper,以确保复制它。例如(这里我配置了 2 个选项只是为了说明):private ObjectMapper objectMapper = Jackson2ObjectMapperBuilder().build()                                          .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)    .setSerializationInclusion(Include.NON_ABSENT);您还可以创建 SpringMockMvc来模拟对它的 HTTP 请求并触发您的控制器,并将其传递给您ObjectMapper,而无需使用繁重的SpringRunner.
随时随地看视频慕课网APP

相关分类

Java
我要回答