how to run/turn off selective tests based on profiles in spring boot

前端 未结 5 960
梦谈多话
梦谈多话 2020-12-10 13:47

I have a spring-boot application for which I am writing IT tests.

The data for the tests comes from application-dev.properties when I activ

5条回答
  •  情书的邮戳
    2020-12-10 14:10

    You can get the active profiles using org.springframework.core.env.Environment: (Beware, it's Kotlin.)

    @Autowired
    private val environment: Environment? = null
    
    private fun isProfileActive(name: String) = environment!!.activeProfiles.contains(name)
    
    @Test fun onlyOnOpenShift {
         org.junit.Assume.assumeTrue(isProfileActive("openshift"));
         ...
    }
    

    If you have a lot of cases where you would use it (which I would suggest might hint that you're doing something wrongly), then it may pay off to decorate the test method with an annotation like @OnlyIfProfileActive("openshift") and process it with your own JUnit extension, like, implementing org.junit.jupiter.api.extension.BeforeTestExecutionCallback and determine if the method should run. In such case, the environment can be obtained from the Spring test runner.

    @Test @OnlyIfProfileActive("openshift")
    fun onlyOnOpenShift {
         ...
    }
    

    Which, I suspect, is what annotations like @IfProfileValue do. But here you would have more control.

    For instance, to make it versatile, it could be an expression evaluated with JEXL or JUEL or such.

    @Test @SpringProfilesCondition("openshift && !mockDatabase")
    fun onlyOnOpenShift {
         ...
    }
    

提交回复
热议问题