我在sources/groovy 中定义了一个Groovy 助手类,我正在尝试使用Spock 进行测试。我尝试测试的类引用了org.springframework.validation.Errors,称为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 注入(inject)它只是为了测试目的,应该给什么类 Errors 是一个接口(interface)?
仅供引用,此方法作为字段验证器的一部分被调用(如果有帮助的话..)并且在生产中运行良好..
谢谢
最佳答案
您可以创建 mock对于 errors
字段并简单地将其设置在您的助手类实例中(假设 errors
字段是公共(public)的)。它应该类似于:
import spock.lang.*
import org.springframework.validation.Errors
MyHelperClass myHelper = new MyHelperClass()
myHelper.errors = Mock(Errors)
关于grails - 如何在 Grails 中测试非 Controller /域/服务类..,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27568196/