0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You should check out @ComponentScan("base-package-where-scan-starts'") annotation and put it at your TestConfiguration class

https://www.javarticles.com/2016/01/spring-componentscan-annotation-example.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.