Search code examples
junitspring-data-jpaobjectmapper

autowired ObjectMapper is null during @DataJpaTest


I want to test my implementation for AttributeConverter using @DataJpaTest.

test code

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class FooRepositoryTest {

    @Autowired
    private FooRepository repository;

    @Test
    void getPojoTest(){
        FooEntity fooEnity= repository.findById("foo");
        FooPojo fooPojo = fooEntity.getJsonPojo()
        //some assertion
        

    }
}

Entity

@Entity
@Data
@NoArgsConstructor
public class FooEntity{

    ....

    @Column(columnDefinition= "JSON")
    @Convert(converter = FooConverter.class)
    private FooPojo data;

    ....
}

Attribute Converter


public class FooConverter implements AttributeConverter<FooPojo, String> {

    @Autowired
    private ObjectMapper mapper;

    @SneakyThrows
    @Override
    public String convertToDatabaseColumn(FooPojo attribute) {
        return mapper.writeValueAsString(attribute);
    }

    @SneakyThrows
    @Override
    public FooPojo convertToEntityAttribute(String dbData) {
        return mapper.readValue(dbData, FooPojo.class);
    }
}

with my code above, when I run getPojoTest(), the @autowired OjbectMapper in Converter is null. When I try the same test with @SpringBootTest instead, it works just fine. I wonder is there any walk-around to use @DataJpaTest and ObjectMapper together.


Solution

  • A better alternative compared to creating your own ObjectMapper is adding the @AutoConfigureJson annotation:

    @DataJpaTest
    @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
    @AutoConfigureJson
    public void FooRepositoryTest {
    
    }
    

    This is also what @JsonTest uses.