在springboottest中从默认的applaton.yml设置测试容器属性的更好方法 [英] Better way to set testcontainer properties from default applicaton.yml in springboottest
本文介绍了在springboottest中从默认的applaton.yml设置测试容器属性的更好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在springboottest中使用posgresql测试容器。由于我有多个测试涉及此测试容器,因此我使用了静态测试容器,它将为1个JUNIT类的所有测试调用一次,并在所有测试执行后关闭。
这是我在EachCallback之前使用参数解析程序实现的。
这种方法的问题是,在默认的应用程序.yml中配置的数据源元数据(如jdbc-url、db名称、主机、端口)不会直接在测试容器属性中使用,相反,我已经对这些值进行了硬编码,因为当时SpringBoot属性不可用。
有没有更好的方法可以使用具有BepreEachCallback功能的静态测试容器,该功能的值是从默认的应用程序.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
}
我希望从Application.yml中读取myDB、sa、sa。我如何才能在这个类中获取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());
}
}
推荐答案
现在似乎有一个专门的项目来集成TestContainers和Spring-Boot。根据我对文档的理解,它对代码应该是透明的,因为一切都是使用Spring Magic完成的。
https://github.com/Playtika/testcontainers-spring-boot
这篇关于在springboottest中从默认的applaton.yml设置测试容器属性的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文