简体   繁体   English

如何在Spock单元测试Grails中测试catch块代码

[英]How to test the catch block code in Spock unit test Grails

Hi i am having my controller action like this and i want to test the catch block of my action tst with the help of Spock Controllers Unit test in 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"
            ........
          }
      }    
}

My test case is like. 我的测试用例就像。

@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
  }
}

But the Catch block code is not executing at all please help me in doing so. 但是Catch块代码根本没有执行,请帮助我。

You would need to throw an exception in your test case. 您将需要在测试用例中引发异常。 You could something like this (not tested): 您可能会这样(未经测试):

@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()
  }
}

If you are testing DataIntegrityViolationException it means you must be inserting and updating some record in the try block. 如果要测试DataIntegrityViolationException则意味着您必须在try块中插入和更新某些记录。

To test catch block you need a test case which violates one of the DB constraints while inserting or updating the record. 要测试catch块,您需要一个在插入或更新记录时违反数据库约束之一的测试用例。

For eg inserting record with duplicate primary key. 例如,插入具有重复主键的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM