默認domain對象中,沒有在constraints中聲明的屬性都是必填項。dom
如User對象測試
<!-- lang: groovy --> package com.example class User { String username String firstname String lastname static constraints { } }
測試代碼code
<!-- lang: groovy --> @TestFor(User) class UserTests { void testSave() { def user = new User(username:'test',firstname:'zhang') assertNotNull user.save() } }
會出現用例測試錯誤,將全部字段都填值後,測試代碼運行正常對象
<!-- lang: groovy --> def user = new User(username:'test',firstname:'zhang',lastname:'san')
在constraints中聲明lastname容許爲空ast
<!-- lang:groovy --> static constraints = { loginName(nullable:false) firstName(nullable:false) lastName(nullable:true) }
再測試不填寫lastname屬性值代碼,測試正常class
<!-- lang:groovy --> def user = new User(username:'test',firstname:'zhang') assertNotNull user.save()