单元测试中的Grails Unique Id约束没有失败

时间:2013-11-14 22:03:00

标签: unit-testing grails gorm

我正在从grails 1.3.6升级到2.2.4并完成所有单元测试。我一直用@Mock注释替换mockDomain等等。我的一个测试是验证ID是否仍然是唯一的,如果id已经存在则会失败。这似乎不再像预期的那样失败。测试如下:

import grails.test.*
import grails.test.mixin.TestFor
import grails.test.mixin.Mock
@Mock(SecurityValue)
@TestFor(SecurityValue)
class SecurityValueTests{
    void testUniqueId() {
        def validEntry = new SecurityValue(id:"id",propertyName:"propertyName",userId:"testUser",componentId:1000)
        validEntry.id = "id"
        def saved = validEntry.save(flush:true, failOnError:true)
        assertNotNull saved
        def validEntry2 = new SecurityValue(id:"id",propertyName:"propertyName1",userId:"testUser3")
        validEntry2.id = "id"
        def saved2 = validEntry2.save(flush:true, failOnError:true)
        def all = SecurityValue.findAll()
        assertNull saved
    }
}

域:

class SecurityValue {

String id
String propertyName
String userId
//String userName
Long componentId

static constraints =
{
    id unique:true, size: 1..100
    propertyName nullable: false, size: 1..100
    userId nullable: false, size: 1..10
    componentId (
        nullable: true, size: 1..10
    )
}

static mapping =
{ 
    table 'pac_sys.security_value'
    id column:'id', type: 'string', generator: 'assigned'
    version false;
}
}

我得到的问题是validEntry2.save行没有失败。我添加了findAll行以查看正在存储的数据,validEntry正好被validEntry2覆盖。

我在这里错过了模拟声明或其他内容吗?


这是应用jonnybot答案后测试的样子。它现在有一个shouldFail方法而不是assertNull并且工作正常。

void testUniqueId() {
    def validEntry = new SecurityValue(id:"id",propertyName:"propertyName",userId:"testUser",componentId:1000)
    validEntry.id = "id"
    mockForConstraintsTests(SecurityValue, [validEntry])
    def validEntry2 = new SecurityValue(id:"id",propertyName:"propertyName1",userId:"testUser3")
    validEntry2.id = "id"
    shouldFail(grails.validation.ValidationException)
    {
        def saved2 = validEntry2.save(flush:true, failOnError:true)
    }
}

1 个答案:

答案 0 :(得分:4)

因为您真正想要做的是测试约束,所以在测试中使用mockForConstraintsTests()和validate()方法。请参阅http://grails.org/doc/2.2.4/guide/testing.html#unitTestingDomains下的“测试约束”。

例如,你可能有

void testUniqueId() {
    def validEntry = new SecurityValue(id:"id",propertyName:"propertyName",userId:"testUser",componentId:1000)
    validEntry.id = "id"
    def saved = validEntry.save(flush:true, failOnError:true)
    assertNotNull saved
    mockForConstraintsTests(SecurityValue, [validEntry])

    def invalidEntry = new SecurityValue(id:"id",propertyName:"propertyName1",userId:"testUser3")
    invalidEntry.id = "id"
    assert !invalidEntry.validate()
}