8

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

4

1 回答 1

0

You can try something like below which worked for me assuming, you are using spring-data-cassandra

First we create another configuration class which will be used for the tests that does not need cassandra connection. It is required as we need to exlude the CassandraDataAutoConfiguration class. Ex:

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

Then we will use this configuration on our test(s). Ex:

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

And there you go.

于 2018-03-13T06:53:51.037 回答