Not able to register JavaTimeModule

1.4k Views Asked by At

I have a spring boot application with version 2.7.3.

I have a util class, that creates a new Object mapper and registers the Javatimemodule class to that.

So in the test case, I try to verify that the registered module is added to the mapper.

This was completely working fine with my previous spring version 2.3. However when upgrading I see this strange issue.

Can some one help here ?

 static {
        mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

  public static ObjectMapper getObjectMapper() {
        return mapper;
    }


@Test
    public void returnsObjectMapper() {
        ObjectMapper objectMapper = Util.getObjectMapper();

        Set<Object> registeredModuleIds = objectMapper.getRegisteredModuleIds();
        assertThat(registeredModuleIds).contains(JavaTimeModule.class.getName());
    }

So when I run the test case with the higher version, I get the following error

java.lang.AssertionError: Expecting UnmodifiableSet:
["jackson-datatype-jsr310"] to contain:
["com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"] but could not find the following element(s):
["com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"]

1

There are 1 best solutions below

0
Andrei Titov On

Judging by the log, ObjectMapper actually has a required module registered in your test, but it's called "jackson-datatype-jsr310" instead of the class name.

AFAIK spring-boot of 2.7.3 uses Jackson version 2.13.3, where JavaTimeModule's default constructor calls super constructor (of SimpleModule class) with a name "jackson-datatype-jsr310", and this name is returned by overridden SimpleModule's getTypeId() method, which is stored then in the ObjectMapper's _registeredModuleIds map.
This name is picked from the com.fasterxml.jackson.datatype.jsr310.PackageVersion static VERSION variable, so if you want your test to pass try something like this:

@Test
public void returnsObjectMapper() {
    ObjectMapper objectMapper = Util.getObjectMapper();
    String javaTimeModuleName = PackageVersion.VERSION.getArtifactId();

    Set<Object> registeredModuleIds = objectMapper.getRegisteredModuleIds();
    assertThat(registeredModuleIds).contains(javaTimeModuleName);
}

Mind that exactly com.fasterxml.jackson.datatype.jsr310.PackageVersion must be imported, because every Jackson package has this class.