0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

@DataJpaTestでJPAのレポジトリをテスト時、使えるDBについて

Posted at

インメモリDBを使用

メリットとしては以下の2点があげられます。

  1. メモリで実行されるため、アプリケーションを再実行するたびにデータが初期化されること
  2. 実際のDBをインストールせずに依存関係を追加ができること

@DataJpaTestに基本的に内蔵されているインメモリDBはH2, HSQL, Derbyがありますが、
今回の記事ではH2を使う方法についてご紹介します。
そのために以下の2点を設定し、テストコードを実行しましょう。

H2の依存関係を追加

・Gradle

dependencies {
    testImplementation 'com.h2database:h2:2.1.214'
}

・Maven

<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>2.7.1</version>
    <scope>test</scope>
</dependency>

他のバージョンは↓を参考にしてください。
https://mvnrepository.com/artifact/org.hsqldb/hsqldb

schema.sql作成

src/test/resourcesの下にテーブルを定義したschema.sqlを追加してください。
ちなみに作成したテーブルにデータを追加する際はdata.sqlを追加し、そこにinsert文を追記しましょう。

物理DBを使用

任意のDBを使用するためにテストクラスに
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)を付与します。
でなると、ご自身のapplication.propertiesに設定したPostgresql,MySQLなどの物理DBに対してレポジトリのテストを行います。

import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class WordsRepositoryTest {
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?