为了账号安全,请及时绑定邮箱和手机立即绑定

Spring boot 2 测试json序列化

Spring boot 2 测试json序列化

白衣染霜花 2021-12-22 19:05:17
我有以下测试,它工作正常。然而在我看来它有点矫枉过正。(也需要一段时间)调出一个完整的 spring 实例来测试一些 json 序列化。@RunWith(SpringRunner.class)@SpringBootTestpublic 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 吗?
查看完整描述

2 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

是的,只需将其初始化为测试的一部分。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.


查看完整回答
反对 回复 2021-12-22
  • 2 回答
  • 0 关注
  • 179 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号