1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SpringBoot】【JUnit】Repository層の単体テスト

Last updated at Posted at 2025-11-17

サンプルコード

Repository層の単体テストを行うクラスを以下のように実装います。
作成したjavaファイルはテストディレクトリ下に配置します。

1. JPA用のテストを行うためのアノテーションをつける
2. Repository をDI(依存性注入)で受け取る
3. 任意のテストメソッド

実装例:

.java
// 1. JPA用のテストを行うためのアノテーションをつける
@DataJpaTest
class BookRepositoryTest {

    // 2. BookRepository をDI(依存性注入)で受け取る
    @Autowired
    BookRepository repo;

    // 3. 任意のテストメソッド
    @Test
    void SavedAndSearched_Test() {

        Book b = new Book();
        b.setTitle("JPA入門");
        b.setAuthor("Taro"); 
        
        repo.save(b);

        Page<Book> page = repo.findByTitleContainingIgnoreCase("JPA", Pageable.ofSize(10));

        assertEquals(1, page.getTotalElements());
    }
}

1. JPA用のテストを行うためのアノテーションをつける

.java
@DataJpaTest
class BookRepositoryTest

Springのコンテキストを起動し、Repository周り(EntityManager / DataSource など)だけを対象にする。
通常はテスト用の組み込みDB(H2など)を使ってテストする。


2. BookRepository をDI(依存性注入)で受け取る

.java
@Autowired
BookRepository repo;

@DataJpaTest によって自動的にテスト用のBeanが用意される


3. 任意のテストメソッド

.java
// テストメソッドであることを示すアノテーション
// ・このメソッドが1つのテストケースとして実行される
@Test
void SavedAndSearched_Test() {

    // ---- ① テストデータを作成 ----
    Book b = new Book();           // 空のBookエンティティを生成
    b.setTitle("JPA入門");          // タイトルをセット
    b.setAuthor("Taro");           // 著者名をセット
    // ※ price や createdAt など、必須でない項目は省略

    // ---- ② テスト対象の処理:保存処理 ----
    repo.save(b);                  // Repository経由でDBにBookを1件保存する

    // ---- ③ テスト対象の処理:検索処理 ----
    // タイトルに "JPA" を含む本を、最大10件までページング検索する
    // ・Containing:部分一致検索
    // ・IgnoreCase:大文字・小文字を区別しない
    Page<Book> page = repo.findByTitleContainingIgnoreCase("JPA", Pageable.ofSize(10));

    // ---- ④ 検証(アサーション) ----
    // 検索結果の件数が1件であることを確認
    assertEquals(1, page.getTotalElements());
}
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?