如何在spock测试中的where子句中调用方法或闭包

时间:2014-01-14 12:40:00

标签: where-clause spock

我正在使用Spock测试atm,我想知道这样的事情是否可能。我的方法不起作用,我想知道你们中是否有人有类似的意图,并找到了办法。

我想调用一个方法或一个闭包,它只能为每个相应的where子句调用,以便设置一些东西。我不能只调用所有这些方法,因为它会破坏我的测试。到目前为止我找到的唯一方法是检查当前状态是什么,并在if语句中相应地调用方法:if(state == SomeStateEnum.FIRST_STATE){somePrivateMethodFromSpec()}但我不知道是否无法完成以更好的方式。我希望我的意图很明确(对不起,我不是母语人士)下面是一些示例代码,可能会更好地了解我想要做什么。提前谢谢。

def 'is this even possible?'() {
    when:
    def resultState = service.someServiceMethod(param)

    then:
    resultState == state

    where:
    state                       | param     | method
    SomeStateEnum.FIRST_STATE   | 'param1'  | somePrivateMethodFromSpec()
    SomeStateEnum.SECOND_STATE  | 'param2'  | someOtherPrivateMethodFromSpec()
}

private def somePrivateMethodFromSpec() {
    someServiceMock.demand.AAA() {}
}

private def someOtherPrivateMethodFromSpec() {
    someServiceMock.demand.BBB() {}
}

def 'or maybe something like this?'() {
    when:
    closure.call()
    def resultState = service.someServiceMethod(param)

    then:
    resultState == state

    where:
    state                       | param     | closure
    SomeStateEnum.FIRST_STATE   | 'param1'  | {println '1'}
    SomeStateEnum.SECOND_STATE  | 'param2'  | {println '2'}
}

解决方案是:

def 'this will work'() {
    "$someOtherPrivateMethodFromSpec"()
    "$somePrivateMethodFromSpec"()
    def resultState = service.someServiceMethod(param)

    then:
    resultState == state

    where:
    state                       | param     | method
    SomeStateEnum.FIRST_STATE   | 'param1'  | "somePrivateMethodFromSpec"
    SomeStateEnum.SECOND_STATE  | 'param2'  | "someOtherPrivateMethodFromSpec"
}

private def somePrivateMethodFromSpec() {
    someServiceMock.demand.AAA() {}
}

private def someOtherPrivateMethodFromSpec() {
    someServiceMock.demand.BBB() {}
}

2 个答案:

答案 0 :(得分:5)

不确定这是否正是您所需要的,但您可以尝试一下:

class MyFirstSpec extends Specification {
  def "let's try this!"() {
    expect:
      "${method}"() == method
    where:
      method << ["method1", "method2"]
  }

  private String method1(){
     return "method1"
  }

  private String method2(){
     return "method2"
  }
}

答案 1 :(得分:3)

为了调用闭包方式,你只需要在where子句的闭包周围添加更多的括号。

E.g。 ({println(&#34; 1&#34;)})

或者作为完整规范。

def 'or maybe something like this?'() {
    when:
    closure.call()
    def resultState = service.someServiceMethod(param)

    then:
    resultState == state

    where:
    state                       | param     | closure
    SomeStateEnum.FIRST_STATE   | 'param1'  | ({println '1'}) 
    SomeStateEnum.SECOND_STATE  | 'param2'  | ({println '2'})
}