我有以下测试,它工作正常。然而在我看来它有点矫枉过正。(也需要一段时间)调出一个完整的 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.
添加回答
举报
0/150
提交
取消