LoginSignup
4
4

More than 3 years have passed since last update.

【SpringBoot】テストクラスで@Autowiredを動かすまで【JUnit5】

Posted at

やること

SpringBoot + JUnit5で、テスト時にコンストラクタパターンのインジェクションを動かすまでやります。

やり方

@ExtendWith(SpringExtension.class)@SpringBootTestを付与すれば動きました。

サンプルコード

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@DisplayName("コンストラクタパターンを動かすテスト")
@ExtendWith(SpringExtension.class)
@SpringBootTest
class AutowiredTest {

    private final AutowiredClass autowiredClass;

    private final String hoge;
    private final String fuga;

    @Autowired
    AutowiredTest(AutowiredClass autowiredClass) {
        this.autowiredClass = autowiredClass;

        hoge = "文字列";
        fuga = "文字列";
    }

    @Test
    @DisplayName("何らかのテスト")
    void uploadFile() {
        assertEquals(hoge, fuga);
    }
}

補足

JUnit5なので、クラス中ではpublicを付けないで色々書けます。
また、コンストラクタはprivateでもインジェクションしてくれます。

4
4
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
4
4