how to call a method or closure in a where clause in a spock test
spock, where-clause
Solution
Not sure if this is exactly what you need but you can try it:
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"
}
}
Problem
I'm working with Spock tests atm and I wonder if anything like this is even possbile. My approaches don't work and I wonder if anyone of you had similiar intentions and found a way. I want to call a method or a closure which must only be called for each respective where-clause in order to setup some things. I can not just call all of these methods as it would ruin my test. The only way I found so far is to check what the current state is and call the method accordingly in an if statement like: if(state==SomeStateEnum.FIRST_STATE){somePrivateMethodFromSpec()} but I wonder if it couldn't be done in a better way. I hope my intentions are clear (sorry, I'm no native speaker) Below is some example code which may be a bit better to understand of what I want to do. Thank you in advance. ``` 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'} } ``` The solution is: ``` 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() {} } ```