![](/img/trans.png)
[英]tSQLt - How to do a unit test on code in an error Catch block of code
[英]How to test the catch block code in Spock unit test Grails
嗨,我有这样的控制器动作,我想借助Grails中的Spock控制器单元测试来测试动作动作的catch块
class AbcController{
def tst(Long id) {
Abc abc = Abc.get(id)
try{
................
println "Try block"
..................
}
catch(DataIntegrityViolationException e){
........
println "Catch block"
........
}
}
}
我的测试用例就像。
@TestFor(AbcController)
@Mock([Abc])
class AbcControllerSpec extends Specification {
void 'Test action catch block'() {
setup:
params.id = 1
when:
controller.tst()
then:
thrown DataIntegrityViolationException
expect:
1==1
}
}
但是Catch块代码根本没有执行,请帮助我。
您将需要在测试用例中引发异常。 您可能会这样(未经测试):
@TestFor(AbcController)
@Mock([Abc])
class AbcControllerSpec extends Specification {
void 'Test action catch block'() {
setup:
this.metaClass.println = { Object value ->
throw new DataIntegrityViolationException()
}
and:
params.id = 1
when:
controller.tst()
then:
DataIntegrityViolationException dive = thrown()
}
}
如果要测试DataIntegrityViolationException
则意味着您必须在try
块中插入和更新某些记录。
要测试catch
块,您需要一个在插入或更新记录时违反数据库约束之一的测试用例。
例如,插入具有重复主键的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.