2

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.

Kiwon Seo
  • 69
  • 5

2 Answers2

2

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.

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
1

From Docs:

@DataJpaTest can be used if you want to test JPA applications. By default it will configure an in-memory embedded database, scan for @Entity classes and configure Spring Data JPA repositories. Regular @Component beans will not be loaded into the ApplicationContext.

silentsudo
  • 6,730
  • 6
  • 39
  • 81
  • Thanks, now I understand that, as the doc said, the objectMapper bean is not created by Spring Context while using `@DataJpaTest`. so i am now using `new ObjectMapper()` for the same test, and it works just fine. – Kiwon Seo Nov 16 '20 at 04:37