精通 Grails: 使用 Grails 进行单元测试(单元测试提速)
2009-11-26 00:00:00 来源:WEB开发网
清单 6. 将会通过的测试,这得益于 mockForConstraintsTests()void testBlank() {
mockForConstraintsTests(User)
def user = new User()
assertFalse user.validate()
}
现在,运行测试来验证它是否会通过,如清单 7 所示:
清单 7. 运行将会通过的测试$ grails test-app -unit User
Environment set to test
Starting unit tests ...
Running tests of type 'unit'
-------------------------------------------------------
Running 1 unit test...
Running test UserTests...PASSED
Tests Completed in 635ms ...
-------------------------------------------------------
Tests passed: 1
Tests failed: 0
-------------------------------------------------------
Tests PASSED - view reports in /testing/test/reports.
要进一步细化单元测试,您可以断言验证会因为特定字段上的特定约束而失败,如清单 8 所示。mockForConstraintsTests() 方法将 errors 集合元编程到域类上。此 errors 集合简化了对是否触发了正确的约束的验证。
清单 8. 断言特定字段上的一个特定约束违规void testBlank() {
mockForConstraintsTests(User)
def user = new User()
assertFalse user.validate()
println "=" * 20
println "Total number of errors:"
println user.errors.errorCount
println "=" * 20
println "Here are all of the errors:"
println user.errors
println "=" * 20
println "Here are the errors individually:"
user.errors.allErrors.each{
println it
println "-" * 20
}
assertEquals "blank", user.errors["name"]
}
更多精彩
赞助商链接