spockframework / spock

The Enterprise-ready testing and specification framework.
https://spockframework.org
Apache License 2.0
3.55k stars 471 forks source link

Multiple "when" block for single "then" block #1545

Open lowcasz opened 1 year ago

lowcasz commented 1 year ago

Is your feature request related to a problem?

I have a lot of situations and I can't find my problem solution in documentation.

The problem is: I have a lot of tests where I expect the same errors and data with similar, or the same given data. In these situations I have everywhere the same given and then blocks for each when block (when is ussualy invoking one method). In these situations I have a lot of boilerplate in test code which is not readable.

Describe the solution you'd like

I tried to use where block and give Clousure, or Runnable, then invoke it in when block, but iI got "Groovyc: Header of data table may only contain variable names"

The best in use will be multiple when: labels for every tested method

In documentation I found only multiple when: then:, but multiple when: for the same then: is needed.

Do you have some idea?

Describe alternatives you've considered

No response

Additional context

No response

leonard84 commented 1 year ago

Can you share MCVE to illustrate your use case a bit more.

Vampire commented 1 year ago

I can imagine two solutions without changes in Spock.

Solution 1: Use helper methods. Put the given: code in a helper method and call it, and put the then: code in a helper method and then call it. Just be aware that in the helper then: methods you do not get implicit assertions, but have to use the assert keyword explicitly for your assertions.

Solution 2: work with closures like you tried, just do it correct. :-D If you get Groovyc: Header of data table may only contain variable names, you most probably tried to have the closure in the first column like

foo       | bar
{ 'bam' } | 'baz'

Unfortunately the Groovy lexer does not see this as the variable name bar and the closure { asdf }, but the method call bar { asdf } which then triggers the error message that you must only have variable names in the data table header. You just have to use a valid syntax. For example one of these:

foo       | bar   ;
{ 'bam' } | 'baz' ;

or

_____________________
; foo       | bar   ;
; { 'bam' } | 'baz' ;

or

bar   | foo
'baz' | { 'bam' }

or

_ | foo       | bar
_ | { 'bam' } | 'baz'