【问题标题】:Grails Unit Tests: Why does this statement fail?Grails 单元测试:为什么这个语句会失败?
【发布时间】:2010-03-30 02:17:21
【问题描述】:

我过去使用 Java 进行开发,现在我正在尝试使用 this slightly dated tutorial 学习 Grails/Groovy。

import grails.test.*

class DateTagLibTests extends TagLibUnitTestCase {

    def dateTagLib

    protected void setUp() {
        super.setUp()
        dateTagLib = new DateTagLib()
    }

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

    void testThisYear() {
        String expected = Calendar.getInstance().get(Calendar.YEAR) 

        // NOTE: This statement fails
        assertEquals("the years dont match and I dont know why.", expected, dateTagLib.thisYear())

    }
}

DateTagLibTests.groovy
注意: 此 TagLibUnitTestCase 适用于 Grails 1.2.1,而不是 tutorial 中使用的版本)

由于某种原因,上述测试失败:

预期: 但实际是:

我尝试将上面的测试替换为以下替代版本的测试,并且测试顺利通过:

void testThisYear() {
    String expected = Calendar.getInstance().get(Calendar.YEAR)
    String actual = dateTagLib.thisYear()

    // NOTE: The following two assertions work:
    assertEquals("the years don\'t match", expected, actual)
    assertTrue("the years don\'t match", expected.equals(actual))
}

这两个版本的测试基本上是一回事吧?

除非 Grails 1.2.1 或 Groovy 中有我不理解的新内容。它们应该属于同一类型,因为这些值都是 Calendar.getInstance().get(Calendar.YEAR)

返回的值

【问题讨论】:

  • @Victor 是的,我对那个测试版很感兴趣!但恐怕我已经被拒之门外了!
  • 是的,它今天刚开始不到 12 小时。你有点错过了火车,但别担心,它会在 7 天内进入公测 :)

标签: grails junit assertions


【解决方案1】:

dateTagLib.thisYear() 返回的对象不能是字符串。

试试

  assertEquals("the years dont match and I dont know why.", expected, dateTagLib.thisYear().toString())

在您的工作示例中,Groovy 正在为您将 .thisYear() 转换为字符串。

打印出 dateTagLib.thisYear().class 以确保。

干杯

【讨论】:

  • 谢谢李(这个问题不是完全重复的......但它很接近...... :-D)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
相关资源
最近更新 更多