SpringBoot disabling DataSourceAutoconfigure error while running Junit Tests
In this tutorial we are going to learn about disabling DataSourceAutoconfigure error while running Junit Tests.
Disabling auto-configuration for your database is one thing, but your application classes rely on (I guess) JPA repositories from Spring Data (they inject it using @Autowired) to work.
If you now disable auto-configuration for your database, your JPA repositories can’t be bootstrapped by Spring Data and hence your service classes fail on startup as they require an available instance: … expected at least 1 bean which qualifies.
I guess you have three choices to solve this:
- Use Testcontainers to provide a real database during your tests and enable auto-configuration of the data related parts again. This would be the best solution as you can test your application with the same database you use in production.
-
Keep disabling auto-configuration, but provide a manual datasource configuration for your tests:
@SpringBootTest class ApplicationIntegrationTest { @TestConfiguration public static class TestConfig { @Bean public DataSource dataSource() { return DataSourceBuilder .create() .password("YOUR PASSWORD") .url("YOUR MSSQL URL") .username("YOUR USERNAME") .build(); } } }
Use @MockBean for all your repositories. This would allow you to completetly work without any database, but you would have to define any interaction with your repositories for yourself using Mockito:
@SpringBootTest class SpringBootStackoverflowApplicationTests { @MockBean private SampleRepository sampleRepository; @MockBean private OtherRepository otherRepository; // your tests }