Spring Boot + JUnitで単体テストをやる


Spring Boot + MySQLでシンプルなWeb REST APIサーバを実装する - Qiita

Outline

Spring Bootで作成したREST APIの単体テストをつくる。
ここでは、JUnitの機能で組める範囲で。

テスト対象のクラスが他のクラスに依存していなければ、JUnitのみでシンプルに組める。
今回は例として、インフラ層で作成したEntityクラスのテストを組む。
Spring BootとJPAでREST APIを実装する(インフラ層編) - Qiita

準備

これまでの手順でプロジェクトを作成(Spring Initializr)していれば、特に準備は必要ない。
既にJUnitは利用できるようになっている(spring-boot-starter-test)。

UserEntityTests.java

UserEntityTests.java
package com.example.springapi.infrastructure;

import com.example.springapi.domain.object.User;
import com.example.springapi.infrastructure.entity.UserEntity;
import org.junit.Before;
import org.junit.Test;

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

public class UserEntityTests {
    private final static String TEST_ID = "test_id";
    private final static String TEST_VALUE = "test_value";

    private User expectedUser;
    private UserEntity expectedUserEntity;

    @Before
    public void setup() {
        this.expectedUser = User.builder()
                .id(TEST_ID)
                .value(TEST_VALUE)
                .build();

        this.expectedUserEntity = UserEntity.builder()
                .id(TEST_ID)
                .value(TEST_VALUE)
                .build();
    }

    @Test
    public void buildTests() {
        UserEntity actual = UserEntity.build(this.expectedUser);

        assertThat(actual.getId()).isEqualTo(this.expectedUser.getId());
        assertThat(actual.getValue()).isEqualTo(this.expectedUser.getValue());
    }

    @Test
    public void toDomainTests() {
        User actual = this.expectedUserEntity.toDomainUser();

        assertThat(actual.getId()).isEqualTo(this.expectedUserEntity.getId());
        assertThat(actual.getValue()).isEqualTo(this.expectedUserEntity.getValue());
    }
}

@Test

テスト実行時に実行されるメソッドになる。
引数exceptedにThrowableクラスを指定することで、Exceptionがthrowされるケースをテストにすることができる。

@Test(expected = IllegalStateException.class)

@Before

@Testの付与されたメソッドの呼び出し前に実行されるメソッドとなる。

org.assertj.core.api.Assertions.assertThat

Assertする書き方のひとつ。
AssertJというライブラリのAPI。(これもJUnit同様、最初から使える。)
メソッドチェーン的に記述することができる。(IDEの補完が聞くので使いやすい。)