Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot 2 testing json serialzation

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?

like image 516
Robbo_UK Avatar asked Dec 05 '25 22:12

Robbo_UK


1 Answers

Use @JsonTest instead of @SpringBootTest

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/json/JsonTest.html

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-json-tests

It will load up the a slice of the context relevant to jackson serialization a few more niceties for testing.

like image 112
Darren Forsythe Avatar answered Dec 08 '25 11:12

Darren Forsythe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!