spring-boot - @IfProfileValue 不适用于 JUnit 5 SpringExtension

标签 spring-boot junit spring-test junit5 spring-profiles

我将 junit5 与 spring-starter-test 一起使用,为了运行 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() {
    }
}

所以应该忽略 contextLoads,因为它没有指定 env 测试组。但测试只是运行并忽略 @IfProfileValue .

最佳答案

我发现 @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 系统属性时才会运行。
@Test
@DisplayName("Application Context should be loaded")
@EnableOnIntegrationTest
void contextLoads() {
}

关于spring-boot - @IfProfileValue 不适用于 JUnit 5 SpringExtension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53718071/

相关文章:

spring-boot - Spring Boot Junit测试main方法

java - org.mockito.exceptions.base.MockitoException : Please ensure that the type 'UserRestService' has a no-arg constructor

java - 在 JUnit 5 中,如何在所有测试之前运行代码

java - 将私钥放入带有变量的 application.yml 中

java - 带有 Logback 的 Spring Boot 应用程序不会作为 Systemd 服务登录到指定位置

mocking - 模拟 Spring 组件

Spring boot @SpyBean 导致测试套件出错,可能是由于上下文未重置的问题

java - Spring集成测试: How to use @Sql with dynamic schema name

java - org.springframework.beans.NotReadablePropertyException :

java - 是否真的有必要在 JUnit 拆卸方法中使对象无效?