Grails唯一约束在保存时失败

时间:2015-02-26 14:29:30

标签: grails

我有以下域名:

class Person {
    String name
    static constraints = {
        name maxSize: 25, blank: false, nullable: false, unique: true
    }
}

现在在这个域上我添加了一个集成测试:

class PersonIntegraionTest {
 void testSavePersonUniqueConstraint() {
    def person = //Loading data from xml
    def node = person[1]
    def person1 = ((Person) node.object)

    personService.save(person1)

    assertNotNull "Person id not present", person1.id

    node = person[2]
    def person2 = ((Person) node.object)
    person2.name = person1.name

    personService.save(person2)

    assertTrue "Person2 have errors", person2.hasErrors()
  }
}

运行此集成测试后,我收到以下错误:

Failure:  |
testSavePersonUniqueConstraint(com.PersonIntegraionTest)
 |
grails.validation.ValidationException: Validation Error(s) occurred during save():
- Field error in object 'com.Person' on field 'name': rejected value [Name2]; codes [com.Person.name.unique.error]

2 个答案:

答案 0 :(得分:1)

在调试模式下运行:

Person.list()

看看到目前为止你得到了什么以及你想要保存什么。

看看你是否已经拥有与新款相同的东西。

答案 1 :(得分:0)

您已将该名称标记为必须是唯一的,因此您可能会运行测试插入名称,现在该名称仍在数据库中。然后再次运行测试失败。在测试运行之前,您的数据库可能尚未清除。你不是从一个已知的州开始的。

作为旁注,您可能想要检查名称字段在第二个断言中是否有错误:

assertTrue "Non-Unique names are not triggering errors", person2.hasErrors() && person2.errors.fieldErrors.name

这样你就知道你在名字字段上发现错误而不是其他错误。

相关问题