@IfProfileValue不能使用JUnit 5 SpringExtension

Chi*_*Dov 6 junit spring-test spring-profiles spring-boot junit5

我使用junit5和spring-starter-test,为了运行spring test我需要使用@ExtendWith而不是@RunWith.但是,@IfProfileValue使用@RunWith(SpringRunner.class)但不使用@ExtendWith(SpringExtension.class),下面是我的代码:

@SpringBootTest
@ExtendWith({SpringExtension.class})
class MyApplicationTests{

    @Test
    @DisplayName("Application Context should be loaded")
    @IfProfileValue(name = "test-groups" , value="unit-test")
    void contextLoads() {
    }
}
Run Code Online (Sandbox Code Playgroud)

所以contextLoads应该被忽略,因为它没有指定env test-grooups.但测试只是运行而忽略了@IfProfileValue.

Chi*_*Dov 7

我发现@IfProfileValue只支持junit4,在junit5中我们将使用@EnabledIf@DisabledIf.

参考https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#integration-testing-annotations-meta

更新:感谢@ SamBrannen的评论,所以我使用junit5内置支持与正则表达式匹配,并将其作为注释.

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@EnabledIfSystemProperty(named = "test-groups", matches = "(.*)unit-test(.*)")
public @interface EnableOnIntegrationTest {}
Run Code Online (Sandbox Code Playgroud)

所以任何具有此注释的测试方法或类只有在具有包含单元测试的测试组的系统属性时才会运行.

@Test
@DisplayName("Application Context should be loaded")
@EnableOnIntegrationTest
void contextLoads() {
}
Run Code Online (Sandbox Code Playgroud)

  • 那是对的.但是,如果您正在使用JUnit Jupiter 5.1或更高版本并且想要检查JVM系统属性,那么最好的选择是内置对"@ EnabledIfSystemProperty"和"@ DisabledIfSystemProperty"的支持. (4认同)