IT

스프링 부트 테스트를 특정 프로필이 활성화된 경우에만 실행되도록 표시할 수 있습니까?

itgroup 2023. 7. 17. 20:53
반응형

스프링 부트 테스트를 특정 프로필이 활성화된 경우에만 실행되도록 표시할 수 있습니까?

저는 두 가지 프로파일을 가지고 있습니다. dev와 default입니다.또한 활성 프로필이 기본값인 경우 일부 테스트를 건너뛰고 싶습니다.어떻게든 이 테스트들을 표시하는 것이 가능합니까?아니면 어떻게 이것을 달성할 수 있습니까?저는 스프링부츠를 사용합니다.이것은 나의 부모님 시험 수업입니다.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyServiceStarter.class, webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT,
        properties = {"flyway.locations=filesystem:../database/h2", "server.port=9100", "spring.profiles.default=dev"})
@Category(IntegrationTest.class)
public abstract class AbstractModuleIntegrationTest { ... }

제 동료가 해결책을 찾았습니다. 따라서 별도의 테스트에 주석을 달 필요가 있다면@IfProfileValue주석:

@IfProfileValue(name ="spring.profiles.active", value ="default")
    @Test
    public void testSomething() {
        //testing logic
    }

이 테스트는 기본 프로필이 활성화된 경우에만 실행됩니다.

업데이트: Junit 5의 경우:

@EnabledIfSystemProperty(named = "spring.profiles.active", matches = "default")

더 많은 정보: https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#integration-testing-annotations-meta

네, 할 수 있습니다.

예를 들어 사용@ActiveProfiles:

@ActiveProfiles("default")
@RunWith(SpringRunner.class)
@SpringBootTest
public class YourTest {
   //tests
}

@IfProfileValueJUNIT 4에서만 작동합니다.만약 당신이 JUNIT 5에 있다면, 이 시간까지 당신이 해야 할 것처럼,@EnabledIf또는@DisabledIf.

예:

@DisabledIf(
    expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}",
    reason = "Disabled on Mac OS"
)

자세한 내용은 문서를 참조하십시오.

아래를 사용하여 명령줄에서 테스트를 실행하려면 다음을 수행합니다.

SPRING_PROFILES_ACTIVE=dev ./gradlew test

위의 모든 것이 제대로 작동하지 않으므로 아래 주석을 사용할 수 있습니다(클래스 또는 단일 테스트 방법).

@DisabledIfEnvironmentVariable(named = "SPRING_PROFILES_ACTIVE", matches = "(dev|default|local)")

스프링 프로파일이 다음과 같이 설정되면 테스트가 비활성화됩니다.dev또는default또는local(정규식)

이 프로필 기반 조건을 사용할 수 있습니다.

@EnabledIf(value = "#{'${spring.profiles.active}' == 'test'}", loadContext = true)

다음은 Junit 5.9.x의 다른 대안입니다.이것은 테스트 방법에서만 작동하고 클래스 레벨에서는 작동하지 않습니다.isProfileActive필요한static. :

@SpringBootTest
public class SomeTest {

    @Autowired
    Environment environment;

    @Test
    @DisabledIf("isProfileActive")
    void testMethod() {}

    boolean isProfileActive() {
        return Arrays.stream(this.environment.getActiveProfiles()).toList().contains("myprofile");
    }
}

언급URL : https://stackoverflow.com/questions/43851621/is-it-possible-to-mark-springboot-tests-so-they-run-only-when-certain-profile-is

반응형