Reputation: 12149
I have the following test and it works ok. However in my mind its a bit of an overkill . (takes a while also) to bring up a full instance of spring to test some json serialization.
@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\"";
}
}
Now I have been able to simplify it by removing SpringRunner. However im not loading the springs jackson configs here.
public class WirelessSerializationTest {
//@Autowired
ObjectMapper objectMapper = new ObjectMapper();
So my question is this. Can I test and load the Springs ObjectMapper instance in the test without needing to load all of Spring up?
Upvotes: 3
Views: 5465
Reputation: 22178
Yes just initialise it as part of your test. You don't need the full SpringRunner
thing if you don't need to have the spring context loaded.
ObjectMapper
is not part of Spring, it is part of Jackson, and you can instantiate it without the Spring context just fine. Just be careful if you have any special configuration you are using in your application for your ObjectMapper
to make sure you replicate it.
For example (here I configured 2 of the options just for illustration):
private ObjectMapper objectMapper = Jackson2ObjectMapperBuilder().build()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.setSerializationInclusion(Include.NON_ABSENT);
You can also create Spring's MockMvc
to simulate HTTP requests to it and trigger your controllers, and pass it your ObjectMapper
, still without having to use the heavy SpringRunner
.
Upvotes: 0
Reputation: 11411
Use @JsonTest
instead of @SpringBootTest
It will load up the a slice of the context relevant to jackson serialization a few more niceties for testing.
Upvotes: 5