this is kind of a duplicate question (Database initialisation before bean creation) but the given answer is somehow not working for me.
For testing purposes I am using a h2-db and therefore I am also looking for a way that (h2)-database scripts are being executed before bean-initialisation, so I have the data ready for integration-tests
In theory the DependsOn behaviour is what I am looking for but for some reason its not working.
Under src/test/resources i have two sql scripts (data.sql and import.sql script)
application.yaml looks the following:
spring:
config:
activate:
on-profile: test
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:undgesund;DB_CLOSE_DELAY=-1
jpa:
hibernate:
ddl-auto: none
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
generate-ddl: false
sql:
init:
mode: always
I have a bean declared in a @Configuration class
@Configuration
public class ConfigClass {
@Bean
@DependsOn("dataSource")
public Map<Integer, SomeEntity> entityMap() {
log.info("loading values into memory...");
final List<SomeEntity> someEntities = this.dao.getAllEntities();
for(SomeEntity someEntity: someEntities) {
this.someEntityMap.put(someEntity.id(), someEntity);
}
}
}
DaoClass is basic and looks like that:
@Service
public class Dao {
@Autowired
private SomeEntityRepository someEntityRepository //basic JpaRepository
public List<SomeEntity> getAllEntities {
return entityRepository.findAll();
}
And I have an test-class
@ActiveProfiles("test")
@ExtendsWith(SpringExtension.class)
@DataJpaTest()
@Import({ConfigClass.class})
class SomeTestClass {
@Autowired
private SomeEntityRepository someEntityRepository
@Test
public void repoTest() {
assertTrue(someEntityRepository.findAll() > 0)
}
What happens now is, that when I am executing the test and the @Bean entityMap gets initialised, the repo is returning no data. But when the test gets executed the repo returns some data and the tests succeeds.
How is it possible that the sql-scripts are getting executed so that data is in the h2-db and when @Bean entityMap is being created, data is actually getting returned?