Skip to content

Instantly share code, notes, and snippets.

@icchan
Created November 17, 2015 07:10
Show Gist options
  • Save icchan/e03b76294e2ef3d8c74d to your computer and use it in GitHub Desktop.
Save icchan/e03b76294e2ef3d8c74d to your computer and use it in GitHub Desktop.
Embedded Cassandra Spring JUnit Test
package net.bubblemix.test;
import org.cassandraunit.spring.CassandraDataSet;
import org.cassandraunit.spring.CassandraUnitTestExecutionListener;
import org.cassandraunit.spring.EmbeddedCassandra;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.QueryLogger;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ CassandraUnitTestExecutionListener.class })
@CassandraDataSet(value = { "myschema.cql" })
@EmbeddedCassandra()
public class EmbeddedCassandraTest {
public static final Logger LOG = LoggerFactory.getLogger(EmbeddedCassandraTest.class);
private static final String HOST = "127.0.0.1";
private static final int PORT = 9142;
private static final String KEYSPACE = "cassandra_unit_keyspace"; // this is a fixed value
public static final boolean QUERY_LOG_ON = true;
private Cluster cluster;
private Session session;
@Before
public void init() {
// Connect to the cluster (using defaults)
cluster = Cluster.builder()
.addContactPoints(HOST)
.withPort(PORT)
.build();
if (QUERY_LOG_ON) {
// Add a query logger
QueryLogger queryLogger = QueryLogger.builder(cluster)
.withConstantThreshold(100)
.build();
cluster.register(queryLogger);
}
session = cluster.connect(KEYSPACE);
}
@After
public void tearDown() {
session.close();
cluster.close();
}
@Test
public void myTest() throws Exception {
Select cql = QueryBuilder.select().from("mytable");
session.execute(cql);
}
}
CREATE TABLE mytable (
id varchar,
value varchar,
PRIMARY KEY(id));
INSERT INTO mytable(id, value) values('ian','Australia');
INSERT INTO mytable(id, value) values('meg','Japan');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment