Unit Test with spring-boot-starter-test and cassandra
Asked Answered
B

1

9

My spring boot web application uses Cassandra DB via the Datastax client and the connection occurs as follow:

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

When I run my Unit Tests, the spring boot application tries to load the CassandraManager Bean and connect to the Cassandra DB which is not up for the Unit Test as I do not need it. I get the following error: [localhost/127.0.0.1:9042] Cannot connect)

Is there a way to avoid loading this Cassandra Manager Bean to run my UT as they do not need to connect to the DB ? Is it a good practice to do so ?

Bemean answered 9/3, 2017 at 15:1 Comment(0)
C
2

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.

Cladoceran answered 13/3, 2018 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.