Throw dynamic exceptions in Spock tests from where block
It's pretty straightforward due to Groovy awesomeness!
Without any further ado:
import spock.lang.Specification
/**
* Created by ravi on 11/14/14.
*/
class SpockDynamicExceptionTest extends Specification {
def "test 1234"() {
given:
def a = 1
when:
exception.newInstance([message])
then:
thrown(RuntimeException)
where:
exception | message
RuntimeException | 'You are awesome'
IOException | 'Yo!'
}
}
Breakdown of what's happening above in case you are new to Spock or Groovy:
Essentially two things are of note above:
-
exception.newInstance([message])
Here I am getting aClass
type and simply usingnewInstance([message])
to instantiate the class with parameter(s):message
-
The
where
block of Spock for data driven tests:
where:
exception | message
RuntimeException | 'You are awesome'
IOException | 'Yo!'
Because the tests are data driven, they will run two times: the first time with RuntimeException
and 'You are awesome'
as arguments to the test method and the second time with IOException
and 'Yo!'
as arguments to the test method!