I downloaded your code and tried to replicate your error (without having the @BeforeAll) and could not get the same result (image). Anyway, if you still get the same problem and you don't like the solution with the Thread.sleep()
, you could use the annotation @DynamicPropertySource
.
@DynamicPropertySource is a method-level annotation that you can use to register dynamic properties to be added to the set of PropertySources in the Environment for an ApplicationContext loaded for an integration test. Dynamic properties are useful when you do not know the value of the properties upfront – for example, if the properties are managed by an external resource such as for a container managed by the Testcontainers project.
I think the problem you are finding is that your application tries to connect to PostgreSQL database before is available (Unable to obtain connection from database: Connection to localhost:32868 refused
). With @DynamicPropertySource
you can test your Spring component even if it depends on something like a database.
You can do the following:
@Container
static PostgreSQLContainer<?> postgresContainer =
new PostgreSQLContainer<>("postgres:17-alpine")
.withDatabaseName("prop")
.withUsername("postgres")
.withPassword("pass");
@DynamicPropertySource
static void registerPgProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgresContainer::getJdbcUrl);
registry.add("spring.datasource.username", postgresContainer::getUsername);
registry.add("spring.datasource.password", postgresContainer::getPassword);
}
For the code I've been guided by this page.
Note: In that same page I've also found that you can use as an alternative Text Fixtures
. I tried that solution as well, but in that case it was giving me the same problem of refused connection. You can try to implement that alternative, see if you have better luck.