Spring Boot 및 Java 11/17이 포함된 테스트 컨테이너
테스트 컨테이너란 무엇입니까?
Testcontainers는 사용자가 Docker 이미지를 실행 및 관리하고 Java 코드에서 제어할 수 있도록 하는 JVM 라이브러리입니다.
통합 테스트는 외부 구성 요소를 실제 Docker 컨테이너로 추가로 실행합니다.
데이터베이스 - PostgreSQL을 Docker 이미지로 실행
모의 HTTP 서버 - MockServer 또는 WireMock Docker 이미지를 사용하는 HTTP 서비스
Redis - 실제 Redis를 Docker 이미지로 실행,
메시지 브로커 - RabbitMQ
AWS - S3, DynamoDB 등
Docker 이미지로 실행할 수 있는 기타 모든 애플리케이션
사용하는 방법?
설정을 위한 추상 클래스의 예
package com.test;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.support.TestPropertySourceUtils;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.ext.ScriptUtils;
import org.testcontainers.jdbc.JdbcDatabaseDelegate;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import org.testcontainers.shaded.com.fasterxml.jackson.databind.SerializationFeature;
import java.util.Optional;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
@Testcontainers
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {com.test.Application.class})
@ActiveProfiles(AbstractBaseIntergrationTestConfiguration.ACTIVE_PROFILE_NAME_TEST)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ContextConfiguration(initializers = AbstractBaseIntergrationTestConfiguration.DockerPostgreDataSourceInitializer.class)
public abstract class AbstractBaseIntergrationTestConfiguration {
protected static final String JDBC_URL = "jdbc.url=";
protected static final String JDBC_USERNAME = "jdbc.username=";
protected static final String JDBC_PASSWORD = "jdbc.password=";
protected static final String JDBC_DRIVER_CLASS_NAME_ORG_POSTGRESQL_DRIVER = "jdbc.driverClassName=org.postgresql.Driver";
protected static final String ACTIVE_PROFILE_NAME_TEST = "TestContainerTests";
//--
public static PostgreSQLContainer<?> postgreDBContainer;
protected ObjectMapper objectMapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
static {
// Init DB Script here
postgreDBContainer = new PostgreSQLContainer<>(IntegrationTestConstants.POSTGRESQL_IMAGE);
postgreDBContainer
.withInitScript(IntegrationTestConstants.INIT_DB_SCRIPT)
.withDatabaseName(IntegrationTestConstants.DB_NAME)
.withUsername(IntegrationTestConstants.DB_USERNAME)
.withPassword(IntegrationTestConstants.DB_PASSWORD);
postgreDBContainer.start();
var containerDelegate = new JdbcDatabaseDelegate(postgreDBContainer, "");
// Adding Database scripts here
ScriptUtils.runInitScript(containerDelegate, IntegrationTestConstants.MISSING_TABLES_SQL);
ScriptUtils.runInitScript(containerDelegate, IntegrationTestConstants.SAMPLE_DATA_SQL);
}
// This class adds the DB properties to Testcontainers.
public static class DockerPostgreDataSourceInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
applicationContext,
JDBC_DRIVER_CLASS_NAME_ORG_POSTGRESQL_DRIVER,
JDBC_URL + postgreDBContainer.getJdbcUrl(),
JDBC_USERNAME + postgreDBContainer.getUsername(),
JDBC_PASSWORD + postgreDBContainer.getPassword()
);
}
}
}
테스트를 작성하는 방법?
@Test
void checkIfUserExistInIdealCase() throws Exception {
request.put("email", "[email protected]");
final MockHttpServletRequestBuilder postObject = getPostRequestExecutorBuilder("http://localhost:8080/v1/checkemail/", Optional.empty());
final MvcResult result = mockMvc.perform(postObject.content(request.toString())).andExpect(status().isOk()).andReturn();
final String content = result.getResponse().getContentAsString();
final SyncResponseDto responseDto = objectMapper.readValue(content, SyncResponseDto.class);
assertThat(responseDto.getResponseReturnCode()).isEqualTo(ResponseReturnCode.USER\_EXIST);
}
장점
단점
참고문헌
Reference
이 문제에 관하여(Spring Boot 및 Java 11/17이 포함된 테스트 컨테이너), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/cricketsamya/testcontainers-with-spring-boot-and-java-1117-gk0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)