我在posgresql中使用posgresql测试容器。由于我有多个涉及这个测试容器的测试,所以我使用了静态测试容器,它将被调用一次,用于所有junit类的测试,并在执行所有测试后关闭。
这是我使用ParameterResolver,BeforeEachCallback实现的。
这种方法的问题是,数据源元数据(如jdbc-url、db名称、主机、默认配置的application.yml中配置的端口)不直接用于测试容器属性,相反,我硬编码了这些值,因为当时没有springboot属性。
是否有更好的方法可以使用具有BeforeEachCallback特性的静态测试容器,其值是从默认的application.yml ?中获取的
@SpringBootTest
class SampleTest extends TestContainerBase {
@Test
void test1() {
//some code
}
}
@ExtendWith(ContainerExtension.class)
@ResourceLock(Environment.ID)
public abstract class TestContainerBase {
protected static String jdbcUrl;
protected static String username;
protected static String password;
@BeforeAll
static void prepareContainerEnvironment(Environment env) {
jdbcUrl = env.getJdbcUrl();
username = env.getUsername();
password = env.getPassword();
}
@DynamicPropertySource
static void dynamicPropertySource(DynamicPropertyRegistry registry) {
registry.add("spring.datasource-.jdbc-url", () -> jdbcUrl);
registry.add("spring.datasource-.username", () -> username);
registry.add("spring.datasource-.password", () -> password);
registry.add("spring.datasource-.driver-class-name", () -> "org.postgresql.Driver");
}
}
public class ContainerExtension implements ParameterResolver, BeforeEachCallback {
// overridden supportsParameter and resolveParameter
}
我希望myDB,sa,sa能从application.yml上读出来。在这个类中,我如何获得application.yml值?由于springboot上下文尚未加载,因此我无法想到获得这些值的任何替代方法。
public class ContainerResource extends Environment {
@Container
protected static PostgreSQLContainer postgreSQLContainer =
new PostgreSQLContainer("artifactory.devtools.syd.c1.macquarie.com:9996/postgres:11")
.withDatabaseName("myDB")
.withUsername("username")
.withPassword("password");
ContainerEnvironmentResource() {
postgreSQLContainer.start();
this.setJdbcUrl(postgreSQLContainer.getJdbcUrl());
this.setUsername(postgreSQLContainer.getUsername());
this.setPassword(postgreSQLContainer.getPassword());
}
}
发布于 2021-10-13 07:04:32
看起来现在有一个专门的项目来集成Testcontainers和Spring。就我所理解的文档而言,它对代码应该是透明的,因为一切都是使用Spring魔法完成的。
https://stackoverflow.com/questions/63228109
复制相似问题