代码之家  ›  专栏  ›  技术社区  ›  switch201

如何使特征方法具有条件

  •  1
  • switch201  · 技术社区  · 7 年前

    在我的测试中,我有一些只需要在某些情况下运行的特性方法。我的代码如下所示:

    class MyTest extends GebReportingSpec{
    
        def "Feature method 1"(){
            when:
            blah()
            then:
            doSomeStuff()
        }
    
        def "Feature method 2"(){
            if(someCondition){
                when:
                blah()
                then:
                doSomeMoreStuff()
            }
        }
    
        def "Feature method 3"(){
            when:
            blah()
            then:
            doTheFinalStuff()
        }
    }
    

    我应该注意的是,我正在使用一个自定义的spock扩展,它允许我运行规范的所有特征方法,即使以前的特征方法失败。

    someCondition 设置为true时,它不会显示在生成结果中。所以我想知道为什么会这样,以及如何使这个特征方法有条件

    3 回复  |  直到 7 年前
        1
  •  3
  •   Leonard Brünings    7 年前

    Spock特别支持有条件执行的特性,请看 @IgnoreIf @Requires .

    @IgnoreIf({ os.windows })
    def "I'll run everywhere but on Windows"() { ... }
    

    class MyTest extends GebReportingSpec {
      @Requires({ MyTest.myCondition() })
      def "I'll only run if myCondition() returns true"() { ... }
    
      static boolean myCondition() { true }
    }
    
        2
  •  1
  •   CommodoreBeard    7 年前

    given , when , then

    您应该始终运行测试,但允许测试正常失败:

    @FailsWith http://spockframework.org/spock/javadoc/1.0/spock/lang/FailsWith.html

    @FailsWith(value = SpockAssertionError, reason = "Feature is not enabled")
    def "Feature method 2"(){
    
        when:
        blah()
        then:
        doSomeMoreStuff()
    }
    

    需要注意的是,该测试将作为 通过 如果该功能已启用且测试实际通过。

        3
  •  0
  •   switch201    7 年前