这几乎是从IBM的Mastering Grails系列文章中逐字记录的。
DateTagLib.groovy:
class DateTagLib {
def thisYear = {
out << Calendar.getInstance().get(Calendar.YEAR)
}
}
DateTagLibTests.groovy:
class DateTagLibTests extends TagLibUnitTestCase {
def dateTagLib
protected void setUp() {
super.setUp()
dateTagLib = new DateTagLib()
}
void testThisYear() {
String expected = Calendar.getInstance().get(Calendar.YEAR)
assertEquals("years do NOT match", expected, dateTagLib.thisYear())
}
protected void tearDown() {
super.tearDown()
}
}
grails test-app DateTagLib
输出:
-------------------------------------------------------
Running 1 unit test...
Running test DateTagLibTests...
testThisYear...FAILED
Tests Completed in 359ms ...
-------------------------------------------------------
Tests passed: 0
Tests failed: 1
-------------------------------------------------------
我尝试匹配类型(int / long / String),但我仍然撞在墙上。
此测试也失败了:
void testThisYear() {
long expected = Calendar.getInstance().get(Calendar.YEAR)
assertEquals("years do NOT match", expected, (long) dateTagLib.thisYear())
}
答案 0 :(得分:7)
请尝试以下
class DateTagLibTests extends TagLibUnitTestCase {
void testThisYear() {
String expected = Calendar.getInstance().get(Calendar.YEAR)
tagLib.thisYear()
assertEquals("years do NOT match", expected, tagLib.out)
}
}
您的原始代码有两个问题:
DateTagLib
。它已通过名为tagLib
thisYear
未返回年份值,而是将其写入out
。在测试中,您可以通过tagLib.out
答案 1 :(得分:0)
out << Calendar.getInstance().get(Calendar.YEAR)
将结果放入out
,如果您要测试此用途def thisYear = { Calendar.getInstance().get(Calendar.YEAR) }