0
0

More than 1 year has passed since last update.

SpringBoot Repository層の単体テスト H2データベースを使うときの設定

Last updated at Posted at 2023-01-25

概要

久しぶりにJavaを触ったところRepository層の単体テストの設定で詰まったので投稿します。
Repositoryの単体テストをするときはH2データベースを使います。
H2データベースを使うことでデータベースにアクセスしないで、単体テストができます。

以下エラー時の画像
Failed to load Application Contextというエラーが出てテストが失敗します。

image.png

開発環境

OS:windows10
IDE:IntelliJ Community
spring-boot-starter-parent 2.75
java : 11

実装方法

pom.xmlにH2データベースを追加する

pom.xml
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

私の場合はmavenにH2が加わってなかったのでエラーになりました。

テストクラスに@DataJpaTest アノテーションを追加する

CustomerRepository.java
@DataJpaTest
public class CustomerRepositoryTest {

    @Autowired
    CustomerRepository customerRepository;
    @BeforeEach
    void setUp(){
//        customerRepository.save(new Customer(1,"pass","test@gmail.com","hogehoge",false));
    }

    @Test
    @DisplayName("Customerを引数とし、saveを実行したとき、Customerが保存される。")
    public void givenCustomer_whenSave_thenSaveDataBase() {
        // given-precondition or Setup
        Customer newCustomer = new Customer(1,"pass","test@gmail.com","hogehoge",false);
        //when - action or the behavior that we are going test
        customerRepository.save(newCustomer);
        //then - verify the output
        assertThat(customerRepository.count()).isGreaterThan(0);
    }
}


動作確認

プロダクトコード

Customer.java
@Entity
@Table(name = "customers")
@Data
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;

    // Loginするときのパスワードして使う
    @Column(nullable = false, length = 64)
    private String password;

    // ログインするときのIDとして使用する
    @Column(nullable = false, unique = true, length = 45)
    private String email;

    // 認証コード
    @Column(name = "verification_code", length = 64)
    private String verificationCode;

    // 初期値はfalse 認証が成功すると trueになる。
    private boolean enabled;

    public Customer(Integer id, String password, String email, String verificationCode, boolean enabled) {
        this.id = id;
        this.password = password;
        this.email = email;
        this.verificationCode = verificationCode;
        this.enabled = enabled;
    }

    public Customer() {
    }
}


CustomerRepository.java
package com.example.restapi.domain.customer;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;


public interface CustomerRepository extends CrudRepository<Customer, Integer> {

    @Query("SELECT c FROM Customer c WHERE c.email = ?1")
    public Customer findByEmail(String email);
    boolean existsByEmail(String email);
    Customer save(Customer customer);
    @Query("SELECT c FROM Customer c WHERE c.verificationCode = ?1")
    Customer  findByVerificationCode(String verificationCode);
    @Query("UPDATE Customer c SET c.enabled = true, c.verificationCode =null WHERE c.id = ?1")
    void enabled(Integer id);
}


結果
テストがOKになり設定がうまくできました。
以下画像
image.png

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