在测试中的 Spring Environment 中使用带有 spring.profiles

根据文档(https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit/jupiter/EnabledIf.html#expression--)你可以使用@EnabledIf测试类或测试方法上的注释,如下所示:


@EnabledIf("${smoke.tests.enabled}")


或者


@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")


其中字符串是 Spring 环境中可用属性的占位符。


假设我有以下application.yml文件:


smoke:

  tests:

    enabled: true

spring:

  profiles:

    active: test

以及以下测试类:


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

@SpringBootTest

public class SomeClassForTests {


    @Autowired SomeType autowiredType;


    @Test

    public void someTest() {

        // test logic...

    }


幕布斯7119047
浏览 118回答 3
3回答

元芳怎么了

要检查 Spring 中属性的确切值Environment,您应该使用以下方法。@EnabledIf(expression = "#{environment['spring.profiles.active'] == 'test'}", loadContext = true)要检查 Spring 中哪些配置文件当前处于活动状态Environment,您应该使用以下方法。@EnabledIf(expression = "#{environment.acceptsProfiles('test', 'someotherprofile')}", loadContext = true)

摇曳的蔷薇

在 SpEL 中使用时,请尝试使用额外的撇号来包装属性:@EnabledIf(value = "#{'${spring.profiles.active}' == 'test'}", loadContext = true)当我尝试使用自定义属性时,我为我工作(终于!)

慕神8447489

您的表达式应如下所示:@EnabledIf(value = "${spring.profiles.active == 'test'}", loadContext = true)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java