2010-07-10 51 views
1

我想測試我的User域類的Grails:測試領域對象的約束

class UserTests extends GrailsUnitTestCase { 

    protected void setUp() { 
     super.setUp() 
     mockForConstraintsTests(User) 
    } 

    void testEmailConstraint() { 

     // Test e-mail validation 
     def user = new User(userRealName: 'bob', passwd: 'foo') 

     // Check null not allowed 
     saveAndVerifyError user, 'email', 'nullable'  
    } 

    private void saveAndVerifyError(User user, String field, String constraintName) { 

     assertFalse user.validate() 
     assertEquals constraintName, user.errors[field] 
    } 
} 

我如何做到這一點的this webpage信息的制約,但是當我運行這個測試我得到的以下例外

java.lang.NullPointerException 
at grails.test.MockUtils$_addValidateMethod_closure83.doCall(MockUtils.groovy:973) 
at grails.test.MockUtils$_addValidateMethod_closure84.doCall(MockUtils.groovy:1014) 
at com.mycompany.security.UserTests.saveAndVerifyError(UserTests.groovy:31) 
at com.mycompany.security.UserTests.this$6$saveAndVerifyError(UserTests.groovy) 
at com.mycompany.security.UserTests$this$6$saveAndVerifyError.callCurrent(Unknown Source) 
at com.mycompany.security.UserTests.testEmailConstraint(UserTests.groovy:18) 

回答

3

原來這是a bug in Grails 1.3.3。以下更改解決此問題

protected void setUp() { 
    super.setUp() 
    PluginManagerHolder.pluginManager = [hasGrailsPlugin: {String name -> true }] as GrailsPluginManager 
    mockForConstraintsTests(User) 
} 

protected void tearDown() { 
    super.tearDown() 
    PluginManagerHolder.pluginManager = null 
}