Skip to content

13.2.3 Testing reactive Cassandra repositories

At this point, it may not come as a surprise that testing reactive Cassandra repositories is quite similar to how you test reactive MongoDB repositories. For example, take a look at IngredientRepositoryTest in the next listing, and see if you can spot how it differs from listing 13.15.

Listing 13.22 Testing the Cassandra IngredientRepository

java
package tacos.data;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.ArrayList;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.cassandra.DataCassandraTest;

import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import tacos.Ingredient;
import tacos.Ingredient.Type;

@DataCassandraTest
public class IngredientRepositoryTest {

  @Autowired
  IngredientRepository ingredientRepo;

  @BeforeEach
  public void setup() {
    Flux<Ingredient> deleteAndInsert = ingredientRepo.deleteAll()
      .thenMany(ingredientRepo.saveAll(
        Flux.just(
          new Ingredient("FLTO", "Flour Tortilla", Type.WRAP),
          new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
          new Ingredient("CHED", "Cheddar Cheese", Type.CHEESE)
      )));
    StepVerifier.create(deleteAndInsert)
          .expectNextCount(3)
          .verifyComplete();
  }

  @Test
  public void shouldSaveAndFetchIngredients() {

    StepVerifier.create(ingredientRepo.findAll())
      .recordWith(ArrayList::new)
      .thenConsumeWhile(x -> true)
      .consumeRecordedWith(ingredients -> {
        assertThat(ingredients).hasSize(3);
        assertThat(ingredients).contains(
          new Ingredient("FLTO", "Flour Tortilla", Type.WRAP));
        assertThat(ingredients).contains(
          new Ingredient("GRBF", "Ground Beef", Type.PROTEIN));
        assertThat(ingredients).contains(
          new Ingredient("CHED", "Cheddar Cheese", Type.CHEESE));
      })
      .verifyComplete();

    StepVerifier.create(ingredientRepo.findById("FLTO"))
      .assertNext(ingredient -> {
        ingredient.equals(new Ingredient("FLTO", "Flour Tortilla", Type.WRAP));
      });
  }

}

Did you see it? Where the MongoDB version was annotated with @DataMongoTest, this new Cassandra version is annotated with @DataCassandraTest. That’s it! Otherwise, the tests are identical.

The same is true for OrderRepositoryTest. Replace @DataMongoTest with @DataCassandraTest, and everything else is the same, as shown here:

java
@DataCassandraTest
public class OrderRepositoryTest {
  ...
}

Once again, consistency between various Spring Data projects extends even into how the tests are written. This makes it easy to switch between projects that persist to different kinds of databases without having to think much differently about how they are developed.

Released under the MIT License.