【问题标题】:How do you make a feature method conditional你如何使特征方法有条件
【发布时间】:2017-10-03 19:48:39
【问题描述】:

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

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,它也不会出现在构建结果中。所以我想知道为什么会这样,以及如何使这个功能方法有条件

【问题讨论】:

  • “我应该注意我正在使用一个自定义 spock 扩展,它允许我运行规范的所有功能方法,即使之前的功能方法失败。”这是正常的行为。您是否在使用 @Stepwise 而并不真正想要它的行为?

标签: spock geb


【解决方案1】:

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】:

    您的测试没有出现在报告中,因为您不能在条件中包含 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()
    }
    

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

    【讨论】:

      【解决方案3】:

      为了解决这个问题,我只是在 if 语句之前放置了一个带有 10 毫秒睡眠的 when/then 块,现在正在执行该功能方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-04
        相关资源
        最近更新 更多