Spring Boot: TestContainers ๐Ÿƒ๐Ÿณ๐Ÿง‘โ€๐Ÿ”ง

๊น€์•„๋ฌด๊ฐœยท2023๋…„ 7์›” 23์ผ
0

Spring Boot ๐Ÿƒ

๋ชฉ๋ก ๋ณด๊ธฐ
56/95
post-custom-banner

๋ณด๊ณ  ๋ฐฐ์šด ์ธ๊ฐ•

CRUD ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ๋•Œ ์–ด๋–ค DB ํ™˜๊ฒฝ์ด ์ข‹์„์ง€์— ๋Œ€ํ•œ ๊ณ ๋ฏผ

๋‹ค์–‘ํ•œ ์„ ํƒ์ง€๋“ค

  1. ์šด์˜ํ™˜๊ฒฝ๊ณผ ์œ ์‚ฌํ•œ ์ŠคํŽ™์˜ DB ( ๊ฐœ๋ฐœ ํ™˜๊ฒฝ DB ) ์‚ฌ์šฉ
    ๐Ÿ‘‰ ๋ฒ„์ „ ์ด์Šˆ, ์ดˆ๊ธฐ ์„ค์ • ๋“ฑ๋“ฑ ์ดˆ๊ธฐ ์„ธํŒ…์ด ๋ณต์žกํ•˜๋‹ค๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค.

  2. ์ธ๋ฉ”๋ชจ๋ฆฌ DB (ex. h2) ์‚ฌ์šฉ
    ๐Ÿ‘‰ ์šด์˜ํ™˜๊ฒฝ๊ณผ ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ํ†ตํ•ฉํ…Œ์ŠคํŠธ ํ™˜๊ฒฝ์—์„  docker ๋˜๋Š” TestContainers ๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ ๋œ๋‹ค.

  3. Docker ์‚ฌ์šฉ
    ๐Ÿ‘‰ container ๊ด€๋ฆฌ๋ฅผ ๋ณ„๋„๋กœ ํ•ด์ฃผ์–ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ด€๋ฆฌํฌ์ธํŠธ๊ฐ€ ๋Š˜์–ด๋‚˜๋Š” ๋‹จ์ ์ด ์žˆ๊ณ ,
    docker๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•ด docker-compose ์™€ ๊ฐ™์€ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ๋ณ„๋„๋กœ ์ž‘์„ฑํ•ด์ฃผ์–ด์•ผํ•˜๋Š” ๋‹จ์ ์ด ์žˆ๋‹ค.

  4. TestContainers ์ด์šฉ
    ๐Ÿ‘‰ TestContainers ๋Š” ์šด์˜ ํ™˜๊ฒฝ๊ณผ ์œ ์‚ฌํ•œ DB ์ŠคํŽ™์œผ๋กœ ๋…๋ฆฝ์ ์ธ ํ™˜๊ฒฝ์—์„œ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์—ฌ ํ…Œ์ŠคํŠธ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.


TestContainers

TestContainers ๋Š”

  • Java ์–ธ์–ด๋งŒ์œผ๋กœ docker container๋ฅผ ํ™œ์šฉํ•œ ํ…Œ์ŠคํŠธ ํ™˜๊ฒฝ ๊ตฌ์„ฑ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
  • ๋„์ปค๋ฅผ ์ด์šฉํ•˜์—ฌ ํ…Œ์ŠคํŠธํ•  ๋•Œ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ์ง์ ‘ ๊ด€๋ฆฌํ•ด์•ผ ํ•˜๋Š” ๋ฒˆ๊ฑฐ๋กœ์›€์„ ํ•ด๊ฒฐํ•ด์ฃผ๋ฉฐ,
    ์šด์˜ ํ™˜๊ฒฝ๊ณผ ์œ ์‚ฌํ•œ ์ŠคํŽ™์œผ๋กœ ํ…Œ์ŠคํŠธ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.
  • ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๊ฐ€ ์‹คํ–‰ ๋  ๋•Œ ์ž๋™์œผ๋กœ ๋„์ปค ์ปจํ…Œ์ด๋„ˆ๋ฅผ ์‹คํ–‰ํ•˜์—ฌ ํ…Œ์ŠคํŠธํ•˜๊ณ ,
    ํ…Œ์ŠคํŠธ๊ฐ€ ๋๋‚˜๋ฉด ์ž๋™์œผ๋กœ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ์ข…๋ฃŒ ๋ฐ ์ •๋ฆฌํ•ด์ค€๋‹ค.
  • ๋‹ค์–‘ํ•œ ๋ชจ๋“ˆ์ด ์กด์žฌํ•œ๋‹ค.

์ ์šฉ

MariaDB์™€ Redis๋ฅผ ๋…๋ฆฝ๋œ ํ™˜๊ฒฝ์—์„œ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ ์ž‘์„ฑ์„ ์œ„ํ•ด TestContainers ์ ์šฉ

testcontainers jdbc ์—ฐ๋™ ๊ณต์‹ ๋ฌธ์„œ ๋งํฌ

build.gradle ์˜์กด์„ฑ ์ถ”๊ฐ€

redis์˜ ๊ฒฝ์šฐ ์ œ๊ณต๋˜๋Š” ๋ชจ๋“ˆ์ด ์—†๊ธฐ ๋•Œ๋ฌธ์— , docker์—์„œ ์ง์ ‘ ๊ฐ€์ ธ์™€์•ผํ•œ๋‹ค.

testImplementation 'org.testcontainers:spock:1.17.1' // test์— ์‚ฌ์šฉํ•  groovy ์–ธ์–ด ๊ธฐ๋ฐ˜ BDD ํ”„๋ ˆ์ž„์›Œํฌ
testImplementation 'org.testcontainers:mariadb:1.17.1'

test/resources/application.yml ์ž‘์„ฑ

spring:
  datasource:
    driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
    url: jdbc:tc:mariadb:10:///

redis ์‹ฑ๊ธ€ํ†ค ์ปจํ…Œ์ด๋„ˆ ์‹คํ–‰ ์ฝ”๋“œ ์ž‘์„ฑ

@SpringBootTest
abstract class AbstractIntegrationContainerBaseTest extends Specification {

    static final GenericContainer MY_REDIS_CONTAINER

    static {
        MY_REDIS_CONTAINER = new GenericContainer<>("redis:6")
                .withExposedPorts(6379)

        MY_REDIS_CONTAINER.start()

        System.setProperty("spring.redis.host", MY_REDIS_CONTAINER.getHost())
        System.setProperty("spring.redis.port", MY_REDIS_CONTAINER.getMappedPort(6379).toString())
    }

}

spock ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, groovy ์–ธ์–ด๋กœ ์ž‘์„ฑ !
java์™€ ์Šคํƒ€์ผ์ด ๊ต‰์žฅํžˆ ๋น„์Šทํ•˜๋‹ค.


post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€