使用spring-boot-starter-test和cassandra进行单元测试

时间:2017-03-09 15:01:33

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

我的Spring启动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,因为他们不需要连接到数据库?这样做是一种好习惯吗?

1 个答案:

答案 0 :(得分:0)

你可以试试下面的东西,这对我有用,假设你正在使用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 */
}

然后你去。