【问题标题】:Unit Test with spring-boot-starter-test and cassandra使用 spring-boot-starter-test 和 cassandra 进行单元测试
【发布时间】:2017-07-30 15:09:55
【问题描述】:

我的 Spring Boot Web 应用程序通过 Datastax 客户端使用 Cassandra DB,连接发生如下:

public CassandraManager(@Autowired CassandraConfig cassandraConfig) {
  config = cassandraConfig;
  cluster = Cluster.builder()
      .addContactPoint(config.getHost())
      .build();
  session = cluster.connect(config.getKeyspace());
}

当我运行单元测试时,spring boot 应用程序会尝试加载 CassandraManager Bean 并连接到不适合单元测试的 Cassandra DB,因为我不需要它。我收到以下错误:[localhost/127.0.0.1:9042] Cannot connect)

有没有办法避免加载这个 Cassandra Manager Bean 来运行我的 UT,因为它们不需要连接到数据库?这样做是个好习惯吗?

【问题讨论】:

    标签: unit-testing cassandra datastax spring-boot-test


    【解决方案1】:

    假设您使用的是spring-data-cassandra,您可以尝试以下对我有用的方法

    首先我们创建另一个配置类,用于不需要 cassandra 连接的测试。它是必需的,因为我们需要排除 CassandraDataAutoConfiguration 类。例如:

    @SpringBootApplication(exclude = {CassandraDataAutoConfiguration.class})
    public class NoCassandraConfig {
    }
    

    然后我们将在我们的测试中使用这个配置。例如:

    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = NoCassandraConfig.class)
    public class UtilitiesTest {
    /*  Lots of tests that does not need DB connection */
    }
    

    你去吧。

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2017-07-28
      • 2017-10-21
      • 2014-07-05
      相关资源
      最近更新 更多