我为我的Spring Boot应用程序开发了集成测试,它与Cassandra一起工作。我使用
我有以下数据库配置 src/test/resources/application.properties:
我可以翻译这段内容。这是关于如何使用Cassandra创建Testcontainers的两种方法的介绍:
CassandraTemplate
与Cassandra进行通信。我有以下数据库配置 src/test/resources/application.properties:
spring.data.cassandra.contact-points=cassandra-host
spring.data.cassandra.port=9042
我可以翻译这段内容。这是关于如何使用Cassandra创建Testcontainers的两种方法的介绍:
1) https://niels.nu/blog/2017/spring-cassandra-integration-tests.html
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = {ExampleApplication.class})
@ContextConfiguration(initializers = CounterIntegrationTestContainers.Initializer.class)
@EnableConfigurationProperties
public class CounterIntegrationTestContainers extends CounterIntegrationTest {
@ClassRule
public static GenericContainer cassandra =
new GenericContainer("cassandra:3")
.withExposedPorts(9042);
public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
EnvironmentTestUtils.addEnvironment(
"testcontainers",
configurableApplicationContext.getEnvironment(),
"cassandra.host=" + cassandra.getContainerIpAddress(),
"cassandra.port=" + cassandra.getMappedPort(9042)
);
}
}
}
2) https://www.baeldung.com/spring-boot-testcontainers-integration-test - 在这个例子中,我们可以看到使用了postgresql容器,但我将其改为Cassandra:
public class BaeldungPostgresqlContainer extends PostgreSQLContainer<BaeldungPostgresqlContainer> {
private static final String IMAGE_VERSION = "postgres:11.1";
private static BaeldungPostgresqlContainer container;
private BaeldungPostgresqlContainer() {
super(IMAGE_VERSION);
}
public static BaeldungPostgresqlContainer getInstance() {
if (container == null) {
container = new BaeldungPostgresqlContainer();
}
return container;
}
@Override
public void start() {
super.start();
System.setProperty("DB_URL", container.getJdbcUrl());
System.setProperty("DB_USERNAME", container.getUsername());
System.setProperty("DB_PASSWORD", container.getPassword());
}
@Override
public void stop() {
//do nothing, JVM handles shut down
}
}
所以,我有一个问题。当我开始测试时,我遇到了一个问题:无法创建CassandraTemplate
bean,因为Cassandra服务器不可用。似乎Spring Data在创建数据库服务器的测试bean之前尝试对Cassandra进行健康检查。
是否有方法可以在Spring Data for Apache Cassandra中使用Testcontainers Cassandra?