gpt4 book ai didi

unit-testing - Grails getErrorCount()返回多个错误,如何获取错误列表?

转载 作者:行者123 更新时间:2023-12-02 14:54:29 25 4
gpt4 key购买 nike

我在grails中对此字段有此约束:

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

我放置maxSize约束,以便grails在html View 中嵌入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,另一个是match。但是我如何为maxSize约束做一个assertEquals?

注意:我正在使用grails 2.0.0

最佳答案

我使用它将所有验证异常解析为一个String,然后在调用代码中执行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;
}

关于unit-testing - Grails getErrorCount()返回多个错误,如何获取错误列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12346417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com