Search code examples
unit-testingspock

Run all blocks when-then, even if one fail


I have method in specification with multiple blocks when-then

def "some test" () {
    given:
    ...

    when: 
    ...
    then: // <-- faild
    ...

    when:
    ...
    then:
    ...
}

If first one block when-then faild, then second one doesn't execute. Is it possible to execute both even if first one faild?


Solution

  • It is not possible and makes no sense, because when you have multiple when in one test case then there is some relation between them and success of the second when is then conditioned by the success of the first when and the behavior to fail the whole test case is wanted.

    If you do not assume that relation then separate it into two or more individual test cases:

    void 'some test'() {
        given:
        ...
        when: 
        ...
        then:
        ...
    }
    
    void 'another test'()
        given:
        ...
        when: 'second when from some test'
        ...
        then: 'second then from some test'
        ...
    }
    

    If you have multiple when+then to share the given section then you can have global setup:

    class MySpec extends Specification {    
        setup() {
            // code from the given section
        }
    
        void 'some test'() {
            ...
        }
    
        void 'another test'() {
            ...
        }
    }
    

    Or you can create shared method which will be called in all test cases when it's needed.

    And if your multiple when blocks differs only in used values then consider using a where block. See the documentation: http://spockframework.org/spock/docs/1.3/data_driven_testing.html#data-tables