1

我对 grails 中的这个字段有这个约束:

businessNumber(matches: '([0-9A-Z]*9)RA([0-9A-Z]*4)', maxSize: 15)

我正在设置 maxSize 约束,以便 grails 在 html 视图上嵌入一个 maxlength 属性。我对如下所示的约束进行了单元测试:

void testBusinessNumberExceedMaxSize(){
        mockChildrenSpecialAllowancesForm.setBusinessNumber("F%G&Hy934F4G6H%55")
        assertFalse (mockChildrenSpecialAllowancesForm.validate())
        assertEquals ("maxSize",mockChildrenSpecialAllowancesForm.errors.businessNumber)
        assertEquals (2, mockChildrenSpecialAllowancesForm.errors.getErrorCount())
    }

然后,它会生成此故障:

testBusinessNumberExceedMaxSize(com.ass.socialservicescm.ChildrenSpecialAllowancesTests)
|  org.junit.ComparisonFailure: expected:<ma[xSize]> but was:<ma[tches]>
    at org.junit.Assert.assertEquals(Assert.java:125)
    at org.junit.Assert.assertEquals(Assert.java:147)
    at com.ass.socialservicescm.ChildrenSpecialAllowancesTests.testBusinessNumberExceedMaxSize(ChildrenSpecialAllowancesTests.groovy:177)

我假设它违反了 2 个约束(因为我的错误计数是 2),一个是 maxSize,另一个是匹配项。但是我如何为 maxSize 约束做一个 assertEquals 呢?

注意:我正在使用 grails 2.0.0

4

2 回答 2

0

我会尝试

assert 'maxSize' in mockChildrenSpecialAllowancesForm.errors.getFieldErrors('businessNumber')*.code
于 2012-09-10T21:15:41.313 回答
0

我使用它来将所有验证异常解析为字符串,然后在调用代码中执行 assertEquals 并将其与结果进行比较。也许有一种更简单的方法,但现在这对我有用。

public static String getErrorString(errors) {
    StringBuffer errorMsg = new StringBuffer();
    errors.allErrors.each {
        if (it instanceof org.springframework.validation.FieldError) {
            if ((it.defaultMessage) == null) {
                errorMsg.append('Error-> ObjectName:' + it.getObjectName() + ' /Field:' + it.getField() + ' /RejectedValue:' + it.getRejectedValue() + ".\n");
            } else {
                errorMsg.append(doReplace((String) it.defaultMessage, it.arguments) + "\n");
            }
        }
    }
    return errorMsg.toString();
}

public static String doReplace(String error, Object[] arguments) {
    int index = 0;
    arguments.each {
        error = error.replace("{" + index + "}", it.toString());
        index++;
    }
    return error;
}
于 2012-09-10T06:59:22.620 回答