Groovy 使用参数化Spock框架进行行为测试

Groovy 使用参数化Spock框架进行行为测试,groovy,spock,Groovy,Spock,我有一套行为测试,结果应该是一样的 def 'behaviour tests for route A'() { when: doA(); then: data == 'Hi' } def 'behaviour tests for route B'() { when: doB(); then: data == 'Hi' } void doA(){ ... } void doB(){ ... } 代码看起来很难看,我宁愿使用参数化测试。除此之外: @Unr

我有一套行为测试,结果应该是一样的

def 'behaviour tests for route A'() {
 when:
   doA();

 then:
  data == 'Hi'
}

def 'behaviour tests for route B'() {
 when:
   doB();

 then:
  data == 'Hi'
}

void doA(){
 ...
}

void doB(){
 ...
}
代码看起来很难看,我宁愿使用参数化测试。除此之外:

@Unroll
def 'behaviour tests for route #name'() {
     when:
       route
    
     then:
      data == 'Hi'

     where:
      name | route
      'A'  | doA()
      'B'  | doB()
}

有办法吗?

您可以使用闭包来提取要在
when
块中执行的代码

class ClosureSpec extends Specification {

  @Unroll
  def 'behaviour tests for route #name'() {
    when:
    def data = route()

    then:
    data == 'Hi'

    where:
    name | route
    'A'  | { doA() }
    'B'  | { doB() }
  }

  def doA() {
    return 'Hi'
  }

  def doB() {
    return 'Hi'
  }
}
或者可以使用groovys dynamic nature传递方法名称

class DynamicSpec extends Specification {

  @Unroll
  def 'behaviour tests for route #name'() {
    when:
    def data = this."do$name"()

    then:
    data == 'Hi'

    where:
    name | route
    'A'  | _
    'B'  | _
  }

  def doA() {
    return 'Hi'
  }

  def doB() {
    return 'Hi'
  }
}
根据用例的不同,我会使用闭包,但是动态方法名有它的用途,特别是如果你想传入参数的话