1
0

SpringBootTest + JUnit5のbeforeAllでDataSourceをinjectionしてテスト用DB初期化

Posted at

解説

下記ドキュメントにあるように、@ExtendWith(SpringExtension.class)@SpringBootTestはこれを含む)とJUnit 5を組み合わせる場合、テストメソッドやライフサイクルコールバックにinjectionが可能となっている。

Dependency injection for test constructors, test methods, and test lifecycle callback methods. ? See Dependency Injection with the SpringExtension for further details.

https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/support-classes.html#testcontext-junit-jupiter-extension より抜粋

Specifically, the SpringExtension can inject dependencies from the test’s ApplicationContext into test constructors and methods that are annotated with Spring’s @BeforeTransaction and @AfterTransaction or JUnit’s @BeforeAll, @AfterAll, @BeforeEach, @AfterEach, @Test, @RepeatedTest, @ParameterizedTest, and others.

https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/support-classes.html#testcontext-junit-jupiter-di より抜粋

以下はTestcontaniersでの使用例。@BeforeAllDataSourceをinjectionしてテーブルに初期データを投入している。@Testでも同様なinjectionをしている。

import javax.sql.DataSource;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.testcontainers.containers.OracleContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@SpringBootTest
@Testcontainers
class SpringBootInitBeforeAll {

  @Container
  @ServiceConnection
  static OracleContainer oracle = new OracleContainer("gvenzl/oracle-xe:21.3.0-slim-faststart")
      .withInitScript("create_table.sql");

  @BeforeAll
  static void beforeAll(
      @Autowired DataSource ds,
      @Autowired ResourceLoader loader) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(
        loader.getResource("classpath:init_sample.sql")
    );
    populator.execute(ds);
  }

  @Test
  void test(@Autowired DataSource ds) {
    Integer v = JdbcClient.create(ds).sql("select count(*) from emp").query(Integer.class).single();
    System.out.println(v);
  }
}

参考リンク

1
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
1
0