我正在尝试为 Command 对象验证编写一些单元测试。 当我的命令对象有很多字段和很多验证规则时,为每个测试用例设置命令对象会变得过于冗长和重复。
假设我有这个命令对象:
class MemberCommand {
String title
String name
String phone
static constraints = {
title(blank: false, inList: ["Mr", "Mrs", "Miss", "Ms"])
name(blank: false, maxSize:25)
phone(blank: false, matches: /\d{8}/)
}
}
我想通过做这样的事情来测试它:
class ValidationTitle extends UnitSpec {
def "title must be one of Mr, Mrs, Miss, Ms"() {
setup:
def memberCommand = new MemberCommand()
// I don't want to do:
// memberCommand.name = "Spock"
// memberCommand.phone = "99998888"
// Instead, I want to disable other constraints, except the one for title
mockForConstraintsTests MemberCommand, [memberCommand]
when:
memberCommand.title = t
then:
memberCommand.validate() == result
where:
t << ["Mr", "Mrs", "Miss", "Ms", "Dr", ""]
result << [true, true, true, true, false, false]
}
}
此测试将失败,因为当调用 memberCommand.validate() 时,将使用所有约束,即使在测试标题“Mr”的情况下也会导致验证错误。 我可以为这个测试设置姓名和电话,但是,我需要在测试姓名验证时设置标题和电话,在测试电话验证时设置标题和姓名。您可以想象,当命令对象的字段更多且规则更复杂时,这会变得更加烦人。
有没有什么方法可以在 grails 中的单元测试(使用 Spock)中禁用约束?
如果没有,对于这种情况还有其他建议吗?
谢谢。
最佳答案
您不能禁用特定的约束验证。但是,您可以为其余属性提供有效值,或者特别是检查 title
属性中的错误。
在第一种情况下,您只需创建一个具有默认(和有效)属性的 map 并从中初始化您的命令:
def validAttributes = [ title: 'Mr', name: 'Spock', phone: '99998888' ]
def "title must be one of Mr, Mrs, Miss, Ms"() {
setup:
def memberCommand = new MemberCommand(validAttributes)
mockForConstraintsTests MemberCommand, [memberCommand]
when:
memberCommand.title = t
then:
memberCommand.validate() == result
where:
t << ["Mr", "Mrs", "Miss", "Ms", "Dr", ""]
result << [true, true, true, true, false, false]
}
拥有一个可验证的“基线”案例也是一种很好的做法(我在测试中始终遵循这种模式)。它表达了您对验证的基本假设。
对于另一种可能性,你会这样做:
def "title must be one of Mr, Mrs, Miss, Ms"() {
setup:
def memberCommand = new MemberCommand()
mockForConstraintsTests MemberCommand, [memberCommand]
when:
memberCommand.title = t
memberCommand.validate()
then:
memberCommand.errors['title'] == result
where:
t << ["Mr", "Mrs", "Miss", "Ms", "Dr", ""]
result << [null, null, null, null, 'not.inList', 'not.inList']
}
关于unit-testing - 禁用 grails 命令对象中的验证约束以进行单元测试(使用 Spock),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6366201/