Grails:测试域对象约束

时间:2010-07-10 12:51:27

标签: unit-testing grails groovy

我正在尝试测试User域类

的约束
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)

1 个答案:

答案 0 :(得分: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
}