It is possible with a few modifications:
- you need to make
expression
a closure (due to some quirks in the AST, closures can't be the first element in a data table, so it must switch places with expectedException
)
- you need to restore the context for the closure with
expression.rehydrate(null, this, this)
- you need to pass the mock instance to the closure as parameter
import spock.lang.*
class Audit {
String getFileName() {
"foo"
}
}
class BatchAudit {
void insertAudit(Audit a) {
println a.getFileName()
}
}
class ASpec extends Specification {
def "test"() {
given:
Audit audit = Mock()
// we need to rehydrate the closure, so that `this` and are correct
expression.rehydrate(null, this, this).call(audit)
BatchAudit bean = new BatchAudit()
when:
bean.insertAudit(audit)
then:
Exception e = thrown()
expectedException.isInstance(e)
where:
expectedException | expression
IllegalStateException | { it.getFileName() >> { throw new IllegalStateException() } }
}
}
Try it out in the Groovy Webconsole.