如何使特征方法成为条件

时间:2017-10-03 19:48:40

标签: spock geb

在我的测试中,我有一些功能方法只需要在某些情况下运行。我的代码看起来像这样:

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扩展,即使以前的特征方法失败,也允许我运行规范的所有特征方法。

我刚才意识到的事情以及我发布这篇文章的原因是因为“功能方法2”由于某种原因没有出现在我的测试结果中,但方法1和3确实如此。即使someCondition设置为true,它也不会出现在构建结果中。所以我想知道为什么会这样,以及如何使这个特征方法成为条件

3 个答案:

答案 0 :(得分:3)

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 }
}

答案 1 :(得分:1)

您的测试未显示在报告中,因为您无法在条件中包含givenwhenthen块。

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

使用@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()
}

重要的是要注意,当测试失败并指定异常时,此测试将报告为传递。如果启用该功能并且测试实际通过,它也将报告为传递

答案 2 :(得分:0)

要解决这个问题,我只需在if语句之前使用10 ms的休眠时间放置一个when / then块,现在该功能方法正在执行

相关问题