Cassandra-Unit

Cassandra-Unit is a Java Utility test tool that helps us write isolated Junit Tests without having to mock or connecting to real cassandra. There are several ways to use the Cassandra-Unit in a Java project. Before to start the entire project is available at my Git Hub account: Cassandra-Unit Git Hub

This blog will describe how using Junit4 rule annotation (@Rule) cassandra-unit can be used.

  1. Create a CQL file describing the table that needs to be created and the data that needs to be inserted.
CREATE TABLE IF NOT EXISTS EMPLOYEE(
 id int,
 name text,

PRIMARY KEY (id)
);

INSERT INTO employee (id, name) VALUES(1, 'Lakshay');
INSERT INTO employee (id, name) VALUES(2, 'George');
INSERT INTO employee (id, name) VALUES(3, 'Andy');
INSERT INTO employee (id, name) VALUES(4, 'Nicole');

   2. Create Junit Test class using CassandraCQLUnit Rule annotation by mentioning the name of the CQL file created in Step 1 and the Cassandra Keyspace name that you prefer. This in itself sets up and starts an embedded Cassandra. This Cassandra unit active instance should be passed to the DAO/Repository class so that the cassandra session can be used to query the started database.

@Rule
public CassandraCQLUnit cassandraCQLUnit = new CassandraCQLUnit(new ClassPathCQLDataSet("cql/employee.cql", "emp_keyspace"));

private EmpRepository empRepository;

@Before
 public void setUp() throws Exception {
     // pass the cassandra session to the class.
     empRepository = new EmpRepository(cassandraCQLUnit.session);
 }

@Test
 public void testFindEmployeeById() throws Exception {
     EmpDetails empExpected = new EmpDetails(1, "Lakshay");
     EmpDetails empGenerated = empRepository.findEmployeeById(1);
     assertEquals(empExpected, empGenerated);
 }

3. The Java class that need to be tested is the following:

public class EmpRepository {

   private Session session;

   public EmpRepository(Session session) {
      this.session = session;
   }


   public EmpDetails findEmployeeById(int id) {
     EmpDetails empDetails = null;
     ResultSet resultSet = session.execute("select * from employee where id="+ id);
     
     for (Row row: resultSet) {
      empDetails = new EmpDetails(row.getInt("id"), row.getString("name"));
       }
    return empDetails;
 }

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s