如何在Spock单元测试中对Java方法和类进行参数化,支持将Audit类设为参数
实现方案
你可以直接将类作为参数放入Spock的where块,同时用闭包封装Mock的动态行为,即可同时实现类、Mock行为、预期异常的全参数化测试,完整示例如下:
import spock.lang.Specification import java.sql.SQLException import org.springframework.dao.DataAccessException class BatchAuditTest extends Specification { def "动态测试不同审计类的insertAudit异常场景"() { given: def audit = GroovyMock(auditClass) // 执行闭包配置Mock行为 mockStubConfig.call(audit) BatchAudit bean = new BatchAudit() when: bean.insertAudit(audit) then: thrown(expectedException) where: auditClass | mockStubConfig | expectedException Audit | { it.getFileName() >> { throw new SQLException() } } | DataAccessException // 可扩展添加其他类的测试用例 // OtherAudit | { it.getOtherField() >> { throw new IOException() } } | OtherBusinessException } }
关键说明
- 类参数化:直接把要Mock的类作为
where块的auditClass参数,创建Mock时动态传入即可,不需要硬编码固定为Audit类 - 动态Mock行为:用闭包作为参数,闭包的入参是实例化好的Mock对象,在given块调用闭包即可完成对应Mock的行为配置,适配不同类的不同Mock规则
- 你可以根据需要在where块扩展任意多组测试参数,覆盖不同类、不同异常场景的测试需求
内容的提问来源于stack exchange,提问作者Harish
相关产品推荐
相关产品推荐

