Reputation: 148
Can we write when
/then
inside if condition in spock test? Code looks like this. Here i am trying to control the calling of when and then.
def testMethod(){
given:
if(some Condition) {
when:
eventOne Occurred
then:
assertion based on eventOne
} else if (some Condition) {
when:
eventTwo Occurred
then:
assertion based on eventTwo
} else {
when:
eventThree Occurred
then:
assertion based on eventThree
}
where:
iteration here.
}
Upvotes: 2
Views: 4202
Reputation: 1042
From the Spock perspective I can't find any restrictions for your specific example. From the readability perspective I don't think it is the best way to use Spock - I agree with answer above.
But please be aware of the following limitation of the Spock labels (from here):
A feature method must have at least one explicit (i.e. labelled) block - in fact, the presence of an explicit block is what makes a method a feature method. Blocks divide a method into distinct sections, and cannot be nested.
So logically you can think of your example as:
Upvotes: 1
Reputation: 42174
What is the purpose of this? The given-when-then
approach was designed to make automated tests easier to understand. The example you shown makes reading and understanding your test hard. And I would even bet it wont compile.
Try keeping your tests simple. where
is used for providing parameters to your test (parameterized test), e.g.
@Unroll
def "should return #result for parameters(#a,#b)"() {
when:
def result = someObject.someMethod(a, b)
then:
result == expected
where:
a | b || expected
null | null || false
"" | "" || false
"test" | "foo" || true
}
The main purpose here is to keep understanding the test logic as simple as possible. If you want to test different combination then you might create separate test method.
Upvotes: 2