Groovy&Grails-代码剪辑-domain对象保存

默认domain对象中,没有在constraints中声明的属性都是必填项。

如User对象


package com.example

class User {
    String username
    String firstname
    String lastname

    static constraints {
    }
}

测试代码


@TestFor(User)
class UserTests {

    void testSave() {
        def user = new User(username:'test',firstname:'zhang')  
        assertNotNull user.save()
    }
}

会出现用例测试错误,将所有字段都填值后,测试代码运行正常


def user = new User(username:'test',firstname:'zhang',lastname:'san')

在constraints中声明lastname允许为空


static constraints = {
    loginName(nullable:false)
    firstName(nullable:false)
    lastName(nullable:true)
}

再测试不填写lastname属性值代码,测试正常


def user = new User(username:'test',firstname:'zhang')
assertNotNull user.save()

你可能感兴趣的:(Groovy&Grails-代码剪辑-domain对象保存)