I tested my Spring Boot app using local PGSQL DB. Now I want to modify tests to use PGSQL running in Testcontainers.
I modified my test configuration class to use Testcontainers and to expose data source connecting to the port returned by Testcontainers:
@TestConfiguration
@SpringBootApplication(exclude = { HazelcastAutoConfiguration.class })
@ComponentScan(basePackages = { "rw.gov.dgie.tm" })
@EntityScan("rw.gov.dgie.tm")
@EnableJpaRepositories(basePackages = { "rw.gov.dgie.tm" })
@EnableAsync(proxyTargetClass = true)
@EnableTransactionManagement
@Testcontainers
public class DbTestConfig {
@Autowired
private DataSource dataSource;
@SuppressWarnings("resource")
@Container
public static ComposeContainer dockerComposeContainer =
new ComposeContainer(new File("../docker/catalog-test.yml"))
.withExposedService("db-catalog", 5432)
.withRemoveVolumes(false)
.withLocalCompose(true)
.waitingFor("db-catalog", new DockerHealthcheckWaitStrategy());
@Bean
public DataSource dataSource(){
DriverManagerDataSource source = new DriverManagerDataSource();
String url = "jdbc:postgresql://" + dockerComposeContainer.getServiceHost("db-catalog", 5432) + ":" + dockerComposeContainer.getServicePort("db-catalog", 5432) + "/db-catalog";
source.setDriverClassName("org.postgresql.Driver");
source.setUrl(url);
source.setUsername("sa");
source.setPassword("sa");
return source;
}
}
I am using the following application-test.yml file:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/db_catalog
username: db_catalog
password: qwerty
hikari:
poolName: Hikari
auto-commit: false
jpa:
show-sql: true
generate-ddl: true
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
ddl-auto: update
generate_statistics: false
However, when running test which was run OK with local DB I get the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Failed to initialize dependency 'dataSourceScriptDatabaseInitializer' of LoadTimeWeaverAware bean 'entityManagerFactory': Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0: Error creating bean with name 'dbTestConfig': Unsatisfied dependency expressed through field 'dataSource': Error creating bean with name 'dataSource': Requested bean is currently in creation: Is there an unresolvable circular reference?
How can I manage that?