【问题标题】:How to test non controller / domain / service classes in Grails ..如何在 Grails 中测试非控制器/域/服务类..
【发布时间】:2014-12-19 14:37:33
【问题描述】:

我在 sources/groovy 中定义了一个 Groovy 助手类,我正在尝试使用 Spock 进行测试。我尝试测试的类引用了 org.springframework.validation.Errors,称为错误 ..

我定义了一个测试,它调用下面显示的一些代码..

def validateSuppliedDocument() {

      // If we create one it's always valid  ..

      if (txn.transactionType.autoCreateDocument) {
          return true
      } else {

          txn.documentHeader =
                  DocumentHeader.findByDocumentReferenceCodeAndDocumentType(txn.documentReferenceCode, txn.transactionType.associatedDocumentType)

          if (!txn.documentHeader) {
              errors.rejectValue('documentReferenceCode', "document.not.found",
                      [txn.documentReferenceCode].toArray(), 'Document not found')
              return false
          }

我的问题是由 'errors.rejectValue' 语句引起的,因为错误实例为 null ..

我怎样才能让 grails 注入它只是为了测试目的,应该给什么类,因为 Errors 是一个接口?

仅供参考,此方法作为字段验证器的一部分被调用(如果有帮助的话..)并在生产中正常工作..

谢谢

【问题讨论】:

    标签: grails testing spock


    【解决方案1】:

    您可以为errors 字段创建一个mock,然后在您的帮助程序类实例中简单地设置它(假设errors 字段是公共的)。应该是这样的:

    import spock.lang.*
    import org.springframework.validation.Errors
    
    MyHelperClass myHelper = new MyHelperClass()
    myHelper.errors = Mock(Errors)
    

    【讨论】:

    • 作为补充问题 .. 我试图模拟 errors.rejectValue 方法 .. errors.rejectValue("documentReferenceCode","document.not.found",messages, "Document not found" ) .. 应该如何定义消息参数?我尝试了字符串...消息,但失败了..有人吗?
    • Sorted is ... 应该是 errors.rejectValue("documentReferenceCode","document.not.found", messages as String) ..
    猜你喜欢
    • 2015-01-07
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2014-06-29
    • 2012-05-03
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多