programing

Spring Boot에게 테스트를 위해 다른 DB를 사용하도록 지시하는 방법은 무엇입니까?

padding 2023. 7. 22. 09:31
반응형

Spring Boot에게 테스트를 위해 다른 DB를 사용하도록 지시하는 방법은 무엇입니까?

Spring Boot에서 응용프로그램 데이터베이스 옆에 있는 MySQL 테스트 데이터베이스를 통합 테스트에 사용하고 싶습니다.현재는 Gradle에 H2 의존성을 추가했기 때문에 H2 데이터베이스를 자동으로 사용하고 있습니다.

예를 들어 이 테스트는 H2 데이터베이스를 사용하여 실행되며, 물리적 보조 데이터베이스를 사용하는 것이 좋습니다.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.observer.media.model.MediaGroup;
import org.observer.media.repository.MediaGroupRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MediaGroupServiceTest {

    @Autowired
    private MediaGroupService mediaGroupService;
    @Autowired
    private MediaGroupRepository mediaGroupRepository;

    @PersistenceContext
    private EntityManager entityManager;

    private MediaGroup mediaGroup = new MediaGroup("name", "ceo", "owner");

    @Test
    public void save() {
        MediaGroup entity = mediaGroupService.saveNew(mediaGroup);

        assertThat(mediaGroupRepository.findByName(mediaGroup.getName())).isEqualTo(entity);
    }
}

메인 애플리케이션에 대한 데이터 소스 구성을 가진 /src/main/java/resources에 application.properties가 있었습니다.

데이터 소스 구성을 사용하여 /src/test/java/resources에 application-test.properties를 데이터베이스에 추가하여 테스트했습니다.추가로, 나는 덧붙였습니다.@ActiveProfiles("test")해당 데이터베이스를 사용해야 하는 테스트.

스프링은 application-test.properties 및 주석에서 test라는 단어를 사용하여 자체 구성합니다.따라서 스프링은 application.properties의 구성을 재정의합니다.

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/database
spring.datasource.username=user
spring.datasource.password=secret
spring.datasource.driverClassName=com.mysql.jdbc.Driver

application-test.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/database_test
spring.datasource.username=user
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

질문에 이미 답이 있지만,

우리는 또한 사용할 수 있습니다.@DataJpaTestJPA 응용 프로그램을 테스트하려는 경우.기본적으로 메모리 내 내장형 데이터베이스를 구성하고 @Entity 클래스를 검색하며 Spring Data JPA 저장소를 구성합니다.일반 @구성요소 콩은 응용프로그램 컨텍스트에 로드되지 않습니다.

스프링 부트 애플리케이션에서 개선된 테스트 중 하나입니다.

문서 읽기: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

메모리 내 데이터베이스는 테스트에서 기본적으로 사용됩니다.이 동작을 비활성화하고 주석을 추가하는 응용 프로그램 구성 데이터베이스를 사용하도록 설정할 수 있습니다.@AutoConfigureTestDatabase(replace = Replace.NONE)자동 구성 데이터 JPA 테스트를 참조하십시오.

그러면 다음을 추가할 수 있습니다.application.properties또는 이에 상당하는src/test/resources또는 다음과 같은 별도의 응용프로그램 파일application-test.properties그리고 그것들에 주석을 달아서 테스트들이 그것을 사용하도록 합니다.@ActiveProfiles("test").

언급URL : https://stackoverflow.com/questions/45653753/how-to-tell-spring-boot-to-use-another-db-for-test

반응형