Spock特征方法中前提条件的好风格是什么?

时间:2014-11-13 09:31:35

标签: spock

在要素方法中,指定when:块中的要素操作,其结果将在后续then:块中进行测试。通常需要准备,这是在given:子句(或setup:或夹具方法)中完成的。包含前置条件同样有用:这些条件不是特征测试的主题(因此不应该在when: - then:expect:中)但是它们断言/记录测试有意义的必要条件。例如,参见下面的虚拟规范:

import spock.lang.*

class DummySpec extends Specification {
  def "The leading three-caracter substring can be extracted from a string"() {
    given: "A string which is at least three characters long"
    def testString = "Hello, World"

    assert testString.size() > 2

    when: "Applying the appropriate [0..2] operation"
    def result = testString[0..2]

    then: "The result is three characters long"
    result.size() == 3
  }
}

这些先决条件的建议做法是什么?我在示例中使用了assert,但许多人对Spec中的assert不满意。

2 个答案:

答案 0 :(得分:7)

我一直在使用expect来表示这种情况:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class DummySpec extends Specification {
  def "The leading three-caracter substring can be extracted from a string"() {
    given: "A string which is at least three characters long"
    def testString = "Hello, World"

    expect: "Input should have at least 3 characters"
    testString.size() > 3

    when: "Applying the appropriate [0..2] operation"
    def result = testString[0..2]

    then: "The result is three characters long"
    result.size() == 3
  }
}

答案 1 :(得分:0)

尽管我不认为这是建议的做法,但另一种有助于保持代码的英语可读性的替代方法是使用Spock提供的描述性and:子句。 / p>

def "The leading three-character substring can be extracted from a string"() {
    given: "A test string"
    def testString = "Hello, World"

    and: "the input should have at least 3 characters"
    testString.size() > 3

    when: "Applying the appropriate [0..2] operation"
    def result = testString[0..2]

    then: "The result is three characters long"
    result.size() == 3
}

由于and:在Spock编译测试方法时没有任何特殊含义,因此您可以在测试方法中随心所欲地使用它。