Webエンジニアのメモ帳

技術的な話を中心に書いています。

【Spring Boot】Cassandraを使った開発で、contextLoads()が通らない場合の対処法

Spring Bootを使っている場合、テストコードにcontextLoads()を記述するのが一般的です。

ところがCassandraを使っている場合はcontextLoads()がそのままだと通りません。この記事では、contextLoads()を通す方法を説明します。

contextLoads()とは

Spring Bootを使った開発では、@SpringBootTestアノテーションを付与したテストクラスを作成し、インジェクションなどが問題なく行えるかを確認するためのcontextLoads()というテストメソッドを記述するのが一般的です。

例えば、以下のような感じのコードです。

なお、Spling Initializerなどを使ってプロジェクトを作成した場合には、自分で書かなくても自動で作成されます。

@SpringBootTest
class ApplicationTests {
  @Test
  void contextLoads() {}
}

ところがこのメソッド、Cassandraを使って開発している場合には、手を加えないとそのままでは通りません。

Cassandraを使っている場合にcontextLoads()を通す方法

今回は、以下のようなコードを例に考えます。

プロダクトコード

build.gradle

以下のように、spring-boot-starter-data-cassandraライブラリを読み込みます。

(dependencies部分のみ記述しています)

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-data-cassandra'
}
エンティティクラス

Cassandraのレコードをマッピングするクラスです。

IDと名前のデータを持つpersonテーブルのデータをマッピングするとします。

import lombok.Value;
import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;

@Table("person")
@Value
public class Person {
  @PrimaryKey private int id;
  private String name;
}
レポジトリクラス

上記のエンティティクラスを扱うレポジトリクラスです。

import org.springframework.data.cassandra.repository.CassandraRepository;

public interface PersonRepository extends CassandraRepository<Person, String> {}

CassandraRepositoryを継承しているので、データの追加や参照などの基本的な処理を行うだけなら、メソッドを記述する必要はありません。

サービス層、コントローラー層

コードは省略しますが、上記のレポジトリクラスをサービス層で使っており、さらにサービス層のクラスをコントローラー層で使っている、という一般的な構成を考えます。

テストコード

@SpringBootTestを付与するテストクラス

@SpringBootTestを付与するテストクラスは、以下のように記述する必要があります。

@SpringBootTest(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration")
class ApplicationTests {
  @MockBean private PersonRepository personRepository;
  @MockBean private CassandraTemplate cassandraTemplate;

  @Test
  void contextLoads() {}
}

ポイントは3つです。

  1. @SpringBootTestアノテーションpropertiesを指定
  2. レポジトリクラスを@MockBean登録する
  3. CassandraTemplateクラスを@MockBean登録する

こうすると、contextLoads()が通るようになります。