@IfProfileValue与JUnit 5 SpringExtension不兼容

14

我使用spring-starter-test和junit5,为了运行spring测试,我需要使用@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() {
    }
}

因为它没有指定环境test-groups,所以应该忽略contextLoads。但是测试仍会运行并忽略@IfProfileValue

1个回答

17

我发现@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 {}

带有这个注解的测试方法或类只在系统属性test-groups包含unit test时才会运行。

@Test
@DisplayName("Application Context should be loaded")
@EnableOnIntegrationTest
void contextLoads() {
}

4
没错。但是,如果你使用的是 JUnit Jupiter 5.1 或更高版本,并且想要检查一个 JVM 系统属性,最好的选择是使用内置的 @EnabledIfSystemProperty@DisabledIfSystemProperty 支持。 - Sam Brannen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接