Search code examples
spring-bootspring-data-jpaintegration-testingjunit5

Loading json into the database during integration tests


I am trying to write some integration tests (Junit5) where I will need to fetch some data from a repository. I would like to pre-populate the database with some json data (I want to avoid sql) before the test start.

After some research I manage to create the test-database.json file inside my resource folder:

[
  {
    "_class": "com.marcellorvalle.scheduler.entity.Professional",
    "id": 1,
    "name": "James Holden"
  },
  {
    "_class": "com.marcellorvalle.scheduler.entity.Professional",
    "id": 2,
    "name": "Gerald of Rivia"
  },
  {
    "_class": "com.marcellorvalle.scheduler.entity.Professional",
    "id": 3,
    "name": "Christjen Avassalara"
  }
]

And also the configuration file:

@Configuration
public class TestConfiguration {
    @Bean
    public Jackson2RepositoryPopulatorFactoryBean getRepositoryPopulator() {
        final Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
        factory.setResources(new Resource[]{new ClassPathResource("test-database.json")});

        return factory;
    }

}

I have a dummy test just to check if everything is ok:

@DataJpaTest
@ExtendWith(SpringExtension.class)
public class IntegrationTest {
    final private ProfessionalRepository repository;

    @Autowired
    public IntegrationTest(ProfessionalRepository professionalRepository) {
        repository = professionalRepository;
    }

    @Test
    public void testFindAll() {
        final List<Professional> result = repository.findAll();
        Assertions.assertEquals(3, result.size());    
    }
}

When I run the test it will fail with no results. Next I added the following to the TestClass:

@ContextConfiguration(classes=TestConfiguration.class)

Now the TestConfiguration is loaded but it can not resolve ProfessionalRepository:

org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [com.marcellorvalle.scheduler.repository.ProfessionalRepository professionalRepository] (...) Failed to load ApplicationContext

Is there any way to read the TestConfiguration without messing the application context?


Solution

  • Instead of using @ContextConfiguration that wipe all your default configs and replace them by the specified classes, try using @Import over your class. That will aggregate your config.