본문 바로가기
Java/Spring

[Spring Boot] 특정 profile에서만 테스트 동작 시키기

by 초이MS 2021. 4. 27.

목적

  • 코딩을 하는 환경과 실제 프로그램이 동작하는 환경이 다른 경우가 대다수이다.
  • 이 경우 통합 테스트 등을 진행하거나 모듈 테스트를 진행할 시에 로컬에서는 동작하나 리얼 혹은 알파에서는 동작하지 않도록 하고싶은 경우가 존재한다.
  • 이러한 경우에 이용할 수 있는 방법을 공유한다.
  • 필자는 spring boot 2.4.4에서 테스트를 진행하였으며 JUnit5에서 적용가능하다.

방법

  1. 해당 요건을 만족시키기 위해 필자는 @EnabledIfEnvironmentVariable를 이용할 것이다. 해당 annotation 이외에도 @DisabledIfEnvironmentVariable, @Enabled, @Disabled 등의 annotation을 이용할 수 있다. annotation 명에서 알 수 있다시피 필자가 사용한 annotation @EnabledIfEnvironmentVariable는 어떤 환경변수가 설정되어 있을 때에만 테스트가 동작하도록 한다.

  2. @EnabledIfEnvironmentVariable annotation을 다음과 같이 추가하였다. 이를 추가하여 intelliJ에서 테스트를 진행하면(intellJ 내부적으로 추가적인 환경변수 설정을 하지 않음) 테스트는 정상적으로 작동하는 것을 볼 수 있다.

    ...
    import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
    ...
    
    ...  
    @EnabledIfEnvironmentVariable(  
    named="SPRING\_PROFILES\_ACTIVE",  
    matches="default"  
    )  
    public class MyTest {  
    ...
    
  3. profile을 다음과 같이 입력하여 리얼 배포용 build시 MyTest를 스킵할 수 있다.(필자는 gradle을 이용)

     $ ./gradlew build -Dspring.profiles.active=deploy

참고

https://stackoverflow.com/questions/43851621/is-it-possible-to-mark-springboot-tests-so-they-run-only-when-certain-profile-is
https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#integration-testing-annotations-junit-jupiter

반응형

댓글