首页 > 解决方案 > Disable whole test (and loading context) based on Spring Property

问题描述

I'm trying to apply TDD in my workflow when I'm working on Spring 5 (not Spring Boot) application, but my running tests take about 45s, which makes my development cycle quite slow. Standard unit tests are super quick, but I have one test which validates Spring context configuration - it takes over 30s on its own.

My idea is to disable this particular test every time during the development cycle and run it just from time to time - e.g. when I create a Docker image with my application/make a commit/push with changes.

So here is what I come up with so far:

  1. Define property when docker-profile is run:

    <profiles>
      <profile>
        <id>docker-build</id>
        <properties>
            <build.profile.id>docker-build</build.profile.id>
        </properties>
        <build>...</build>
      </profile>
    </profiles>
    
  2. Use it in test.properties:

    app.profile=${build.profile.id}
    
  3. Use @EnabledIf annotation in test:

     @TestPropertySource("classpath:test.properties")
     @SpringJUnitConfig( classes = MainConfiguration.class )
     @EnabledIf("#{'${app.profile}' == 'docker-build'}")
     public class SpringConfigTest {
       ...
     }
    

And it doesn't seem to work - I can be wrong, but app.profile property doesn't seem to be available when I call it in @EnabledIf. Or maybe I took a wrong route and there is simpler way to disable this particular test - I run it as mvn test at the moment. I would like to know why app.profile property isn't visible for @EnabledIf though.

Edit I've discovered I can skip the first two steps and define property in command line:

mvn -Dapp.profile=docker-build test

But not sure why I can't get property from test.properties file

标签: springtesting

解决方案


我相信您需要在这种情况下为 @EnabledIf 的春季版本加载上下文来评估表达式。所以它会是:

@EnabledIf(expression = "#{'${app.profile}' == 'docker-build'}", loadContext = true)

还要确保属性文件包含在启用过滤的 maven testResources 中:

    <build>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
    </build>

我认为上面应该解决您面临的特定财产问题。但是由于这不会跳过加载 spring 上下文,也许更好的方法是在 maven 配置文件中配置以跳过基于包或测试类名称的测试 - 类似于Is there a way to tell surefire to skip tests in a certain package?


推荐阅读