Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Testcontainersでコンテナを使ったテストを実行しよう

H.Naka
June 19, 2022

 Testcontainersでコンテナを使ったテストを実行しよう

JJUG CCC 2022 Spring 6月19日開催
[Track A] 10:25- #jjug_ccc_a
#jjug_ccc
Testcontainersでコンテナを使ったテストを実行しよう

H.Naka

June 19, 2022
Tweet

More Decks by H.Naka

Other Decks in Programming

Transcript

  1. ४උ ґଘੑͷ֬ೝ w ϓϩδΣΫτΛੜ੒͢ΔͱQPNYNMʹ5FTUDPOUBJOFSTͷґଘੑ͕ͭೖͬͯ ͍·͢ w ্͸+6OJUͱ૊Έ߹ΘͤΔϥΠϒϥϦɺԼ͸1PTUHSF42-ͷϞδϡʔϧΛఏ ڙ͢ΔϥΠϒϥϦͰ͢ <dependency> <groupId>org.testcontainers</groupId>

    <artifactId>junit-jupiter</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>postgresql</artifactId> <scope>test</scope> </dependency>
  2. ίϯςφΛ࣮ߦ͠Α͏ ࣮ߦͯ͠ΈΑ͏ w ίϯςφͷఆ͕ٛऴΘͬͨΒςετΛ࣮ߦ͠·͢ w ςετΛ࣮ߦ͢Δͱ࠷ॳʹ5FTUDPOUJBOFST͕ఆٛ͞ΕͨίϯςφΛىಈ͠· ͢ w ͦͷޙɺςετϝιου͕ݺͼग़͞Ε·͢ w

    ͨͬͨ͜Ε͚ͩ४උͰςετͰར༻͢Δ؀ڥ͕ηοτΞοϓ͞Ε·ͨ͠ @Test void ίϯςφ͕ಈ͍͍ͯΔ͜ͱ() { assertTrue(postgresqlContainer.isRunning()); }
  3. ίϯςφ࣮ߦͷิ଍ खಈͰͷίϯςφىಈ w ΞϊςʔγϣϯΛར༻͠ͳ͍৔߹ɺOFXͨ͠ίϯςφΠϯελϯεͷTUBSUϝ ιουΛݺͼग़͢͜ͱͰίϯςφΛىಈ͢Δ͜ͱ͕Ͱ͖·͢ w ͜ͷํ๏Ͱىಈͨ͠৔߹Ͱ΋ίϯςφͷޙ࢝຤͸5FTUDPOUBJOFST͕ߦͬͯ͘ Ε·͢ // ࣮ߦ͢Δίϯςφͷఆٛ

    PostgreSQLContainer postgresqlContainer = (PostgreSQLContainer) new PostgreSQLContainer("postgres:14.2") .withDatabaseName("todo") .withInitScript("todo.sql"); // ىಈ postgresqlContainer.start();
  4. 4QSJOH#PPU5FTU σʔλϕʔεͷ઀ଓఆٛΛઃఆ w σʔλϕʔεͷ઀ଓઃఆ͸ɺ%ZOBNJD1SPQFSUZ4PVSDFΛ෇༩ͨ͠ϝιου ಺Ͱઃఆ͠·͢ w ઀ଓ৘ใ͸શͯίϯςφΠϯελϯε͔ΒऔಘՄೳͰ͢ w ༨ஊͰ͕͢͜ͷΞϊςʔγϣϯ͸4QSJOH͕5FTUDPOUBJOFSTͷͨΊʹ༻ҙͨ͠ ΋ͷͰ͢

    @DynamicPropertySource static void jdbcProperties(DynamicPropertyRegistry registry) { registry.add("spring.datasource.url", postgresqlContainer::getJdbcUrl); registry.add("spring.datasource.username", postgresqlContainer::getUsername); registry.add("spring.datasource.password", postgresqlContainer::getPassword); }
  5. 4QSJOH#PPU5FTU ςετ࣮ߦ w ςετϝιουͰ4QSJOHͷαʔϏεΫϥεΛݺͼग़͢ςετΛهड़͠·͢ w ςετΛىಈ͢Δͱίϯςφͷσʔλϕʔεͱ4QSJOH͕ىಈ͠ɺςετϝι ου಺ͷॲཧ͕͓͜ͳΘΕ·͢ w ͜ΕͰσʔλϕʔεΛ༻͍ͨΞϓϦέʔγϣϯͷ݁߹ςετ͕ߦ͑·ͨ͠ @Autowired

    private TodoService service; @Test @Order(1) void addTodo() { String task = "🐱ʹ͝൧Λ΋Β͏"; Todo todo = service.addTodo(task); assertEquals(task, todo.task()); assertEquals("Waiting", todo.status()); }
  6. 4QSJOH#PPU5FTUิ଍ &YUFOTJPOΫϥεͰͷ࣮ߦ w ࠓճ͸ΞϊςʔγϣϯΛ༻͍ͨγϯϓϧͳํ๏Λ঺հ͠·ͨ͠ w Ξϊςʔγϣϯͷ৔߹͸֤ΫϥεͰίϯςφͷఆٛΛߦ͏ඞཁ͕͋Γ·͕͢ɺ ͜ͷఆٛΛ+6OJUͷ&YUFOTJPOΛ༻͍ͯू໿͢Δํ๏΋͋Γ·͢ w (JUIVCʹαϯϓϧͷίʔυ͕͋Γ·͢ͷͰࢀরͯ͠Έ͍ͯͩ͘͞ public

    class PostgresExtension implements BeforeAllCallback, AfterAllCallback { private PostgreSQLContainer<?> postgresqlContainer; @Override public void beforeAll(ExtensionContext context) { postgresqlContainer = (PostgreSQLContainer) new PostgreSQLContainer("postgres:14.2") .withDatabaseName("todo"); postgresqlContainer.start(); System.setProperty("spring.datasource.url", postgresqlContainer.getJdbcUrl()); System.setProperty("spring.datasource.username", postgresqlContainer.getUsername()); System.setProperty("spring.datasource.password", postgresqlContainer.getPassword()); }