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

Behaviour test using parametrised Spock framework

我有一组行为测试应该会产生相同的结果

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 的动态特性来传入方法名

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

根据 use-case 我会使用闭包,但动态方法名称有其用途,特别是如果你想传入参数。