解説
下記ドキュメントにあるように、@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.
Specifically, the
SpringExtension
can inject dependencies from the test’sApplicationContext
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.
以下はTestcontaniersでの使用例。@BeforeAll
でDataSource
を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);
}
}
参考リンク
- https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/support-classes.html#testcontext-junit-jupiter-extension
- https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/support-classes.html#testcontext-junit-jupiter-di
- https://agohack.com/how-to-execute-sql-scripts-once-before-in-spring-test/
- https://stackoverflow.com/questions/29340286/how-to-autowire-field-in-static-beforeclass