Grails单元测试:为什么此声明失败?

问题描述:

我以前在Java中开发过,现在我正在尝试使用this slightly dated tutorial来学习Grails/Groovy。Grails单元测试:为什么此声明失败?

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是用于tutorial使用的Grails 1.2.1而不是版本)

出于某种原因,上述的测试失败,并:

预计:< 2010>但是:< 2010>

我试图替换上面与测试以下替代版本的测试,并且测试通过就好:

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)

+0

复制我的坏! – leeand00 2010-03-30 02:21:46

+0

@Victor是的,我对这个测试版非常感兴趣!但是我害怕我被拒之门外! – leeand00 2011-01-20 01:58:18

+1

是的,它今天刚刚开始不到12个小时。你有点错过了火车,但不用担心,它会在7天内进入公测阶段:) – greatwolf 2011-01-20 02:02:44

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

尝试

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

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

打印出dateTagLib.thisYear()。类来确定。

欢呼

+0

谢谢Lee(这个问题不是一个确切的副本......但它虽然接近......) – leeand00 2010-03-30 13:15:13