Saturday, June 7, 2014

Using Stubbed Cassandra's new JUnit rule

In my first post about unit testing Java applications that use Cassandra you had to start Scassandra before your test, reset it between tests and finally stop it before it after your tests. Since then I've accepted a pull request which hides all this away in a JUnit rule.

So the old code in your tests looked like this for starting Scassandra:

private static PrimingClient primingClient;
private static ActivityClient activityClient;
private static Scassandra scassandra;
@BeforeClass
public static void startScassandraServer() throws Exception {
scassandra = ScassandraFactory.createServer();
scassandra.start();
primingClient = scassandra.primingClient();
activityClient = scassandra.activityClient();
}

This for stopping Scassandra:

@AfterClass
public static void shutdown() {
scassandra.stop();
}

And this for resetting Scassandra between tests:

@Before
public void setup() {
activityClient.clearAllRecordedActivity();
primingClient.clearAllPrimes();
}

Now you can simply do this:

@ClassRule
public static final ScassandraServerRule scassandra = new ScassandraServerRule();
@Rule
public final ScassandraServerRule resetScassandra = scassandra;
private static PrimingClient primingClient = scassandra.primingClient();
private static ActivityClient activityClient = scassandra.activityClient();

Assigning it to a ClassRule means that it will start Scassandra before all your tests and stop it after all your tests. Then assigning it to a regular Rule means that the Activity client and Priming client will be reset between tests.

No comments: