![](/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.