Search code examples
javagroovyspock

Spock @IgnoreIf based on properties file


I want to ignore a test by taking values from properties file and then feeding them into the IgnoreIf predicate. Is this possible? If not, is there a workaround?


Solution

  • The Spock Manual, chapter "Extensions", describes how to use bound variables like sys, env, os, jvm. But basically you can put any Groovy closure there.

    If you specify environment variables or system properties on the command line when running your tests, you can just use env or sys in order to access them. But if you absolutely want to read the properties from a file, just use a helper class like this:

    File spock.properties:

    Probably you want to put the file somewhere under src/test/resources if you build with Maven.

    spock.skip.slow=true
    

    Helper class reading the properties file:

    class SpockSettings {
        public static final boolean SKIP_SLOW_TESTS = ignoreLongRunning();
    
        public static boolean ignoreLongRunning() {
            def properties = new Properties()
            def inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("spock.properties")
            properties.load(inputStream)
            inputStream.close()
            //properties.list(System.out)
            Boolean.valueOf(properties["spock.skip.slow"])
        }
    }
    

    Test using the helper class:

    import spock.lang.IgnoreIf
    import spock.lang.Specification
    import spock.util.environment.OperatingSystem
    
    class IgnoreIfTest extends Specification {
        @IgnoreIf({ SpockSettings.SKIP_SLOW_TESTS })
        def "slow test"() {
            expect:
            true
        }
    
        def "quick test"() {
            expect:
            true
        }
    
        @IgnoreIf({ os.family != OperatingSystem.Family.WINDOWS })
        def "Windows test"() {
            expect:
            true
        }
    
        @IgnoreIf({ !jvm.isJava8Compatible() })
        def "needs Java 8"() {
            expect:
            true
        }
    
        @IgnoreIf({ env["USERNAME"] != "kriegaex" })
        def "user-specific"() {
            expect:
            true
        }
    }