为什么这个(琐碎的)单元测试失败了?

时间:2010-02-18 20:17:43

标签: java grails groovy junit taglib

这几乎是从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())
}

2 个答案:

答案 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) }