开发者

Why is this (trivial) unit test failing?

开发者 https://www.devze.com 2022-12-20 19:40 出处:网络
This was taken nearly verbatim from IBM\'s Mastering Grails series. DateTagLib.groovy: class DateTagLib {

This was taken nearly verbatim from IBM's Mastering Grails series.

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)
        assertEqua开发者_如何学Pythonls("years do NOT match", expected, dateTagLib.thisYear())
    }

    protected void tearDown() {
        super.tearDown()
    }
}

grails test-app DateTagLib output:

-------------------------------------------------------
Running 1 unit test...
Running test DateTagLibTests...
                    testThisYear...FAILED
Tests Completed in 359ms ...
-------------------------------------------------------
Tests passed: 0
Tests failed: 1
-------------------------------------------------------

I tried matching the types (int/long/String), but I'm still banging my head against the wall.

This test also fails:

void testThisYear() {
    long expected = Calendar.getInstance().get(Calendar.YEAR)
    assertEquals("years do NOT match", expected, (long) dateTagLib.thisYear())
}


Try the following instead

class DateTagLibTests extends TagLibUnitTestCase {

    void testThisYear() {
        String expected = Calendar.getInstance().get(Calendar.YEAR)
        tagLib.thisYear()
        assertEquals("years do NOT match", expected, tagLib.out)
    }

}

Your original code has 2 problems:

  • You should not instantiate DateTagLib explicitly. It is already available through a property of the test class named tagLib
  • thisYear does not return the year value, it writes it to out. Within a test you can access the content written to the output via tagLib.out


out << Calendar.getInstance().get(Calendar.YEAR) puts the result into out, if you want to test this use def thisYear = { Calendar.getInstance().get(Calendar.YEAR) }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号