Stephan Prätsch
Stephan Prätsch

Reputation: 119

SpringBoot: Unit Test with Cassandra

I'd like to test my SpringBoot application that uses cassandra as a CrudRepository. I ended up with

/*
 * https://github.com/jsevellec/cassandra-unit/wiki/Spring-for-Cassandra-unit
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan
@ContextConfiguration(value = { "classpath:/default-context.xml" })
@TestExecutionListeners({ CassandraUnitTestExecutionListener.class })
@CassandraDataSet(value = { "setupTables.cql" }, keyspace = "keyspaceToCreate")
@CassandraUnit
public class ApplicationTests {

    @Autowired
    MyCassandraRepository repo;

    @Test
    public void contextLoads() {

        System.out.println(repo.findAll());

    }

}

with

    <dependency>
        <groupId>org.cassandraunit</groupId>
        <artifactId>cassandra-unit-spring</artifactId>
        <version>3.0.0.1</version>
        <scope>test</scope>
    </dependency>

and

CREATE TABLE MY_CASSANDRA_ENTRY (
  MY_CASS_STRING varchar PRIMARY KEY
)

This leads to

com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9142 (com.datastax.driver.core.exceptions.InvalidQueryException: unconfigured table schema_keyspaces))

If I use an older version of cassandra-unit-spring

    <dependency>
        <groupId>org.cassandraunit</groupId>
        <artifactId>cassandra-unit-spring</artifactId>
        <version>2.1.9.2</version>
        <scope>test</scope>
    </dependency>

it ends with a NullPointerException because the value repo is not injected.

Sources https://github.com/StephanPraetsch/spring.boot.cassandra.unit.test

Upvotes: 4

Views: 8758

Answers (1)

mp911de
mp911de

Reputation: 18119

CassandraUnit starts on port 9142. Spring Boot defaults to port 9042. You need to set the port and the keyspace name so the Cassandra driver can pickup the right connection details.

You need to change two things in your test:

  1. Please use @SpringBootTest instead of @EnableAutoConfiguration. That enables a couple of other things like configuration property support which you will need in step 2.

  2. Create src/test/resources/application.properties and set the port and keyspace name.

spring.data.cassandra.port=9142
spring.data.cassandra.keyspace-name=keyspaceToCreate

This will configure the correct port and keyspace.

Alternatively, you could specify properties using

@SpringBootTest({"spring.data.cassandra.port=9142",
                 "spring.data.cassandra.keyspace-name=keyspaceToCreate"})

Upvotes: 3

Related Questions