我正在使用Spock进行单元测试。我想要动态测试Java方法和类,如下面的示例所示。Audit是一个Java类。此外,如果可能的话,我还想让Audit类成为一个参数
given:
Audit audit = GroovyMock()
expression
BatchAudit bean = new BatchAudit()
when:
bean.insertAudit(audit)
then:
thrown(exc)
where:
expression | exc
audit.getFileName() >> {throw new SQLException(new Throwable())} | DataAccessException发布于 2021-11-27 10:47:10
只需进行一些修改即可实现:
对于闭包,您需要将其设置为闭包(由于AST中的一些怪癖,闭包不能是数据表中的第一个元素,因此它必须与expectedException)
expression.rehydrate(null, this, this)
传递给闭包
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() } }
}
}在Groovy Webconsole中尝试一下。
https://stackoverflow.com/questions/70129549
复制相似问题