2

これは、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())
}
4

2 に答える 2

7

代わりに以下を試してください

class DateTagLibTests extends TagLibUnitTestCase {

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

}

元のコードには 2 つの問題があります。

  • DateTagLib明示的にインスタンス化しないでください。という名前のテストクラスのプロパティを通じて既に利用可能ですtagLib
  • thisYearは年の値を返さず、に書き込みますout。テスト内で、出力に書き込まれたコンテンツにアクセスできますtagLib.out
于 2010-02-18T20:43:33.233 に答える
0

out << Calendar.getInstance().get(Calendar.YEAR)outこの使用法をテストしたい場合は、結果を に入れますdef thisYear = { Calendar.getInstance().get(Calendar.YEAR) }

于 2010-02-18T20:29:54.980 に答える