技术开发 频道

精通 Grails: 测试 Grails 应用程序

  测试定制的 TagLib

  接下来是最后一个需要处理的用户场景。您已经在 create 和 edit 视图中成功地处理了 checkIn 和 checkOut 的时间戳部分,但它在 list 和 show 视图中仍然是错误的,如图 12 所示:

  图 12. 默认的 Grails 日期输入(包括时间戳)  

  最简单的解决办法是定义一个新的 TagLib。您可以利用 Grails 已经定义的 标记,但创建一个自己的定制标记也很容易。我想创建一个可以以两种方式使用的 标记。

  一种形式的 标记打包一个 Date,并接受一个接受任何有效 SimpleDateFormat 模式的定制格式属性:

<g:customDateFormat format="EEEE">${new Date()}</g:customDateFormat>

  因为大多数用例都以美国的 “MM/dd/yyyy” 格式返回日期,所以如果没有特别指定,我将采用这种格式:

<g:customDateFormat>${new Date()}</g:customDateFormat>

  现在,您已经知道了每个用户场景的需求,那么请输入 grails create-tag-lib Date(如清单 13 所示),以创建一个全新的 DateTagLib.groovy 文件和一个相应的 DateTagLibTests.groovy 文件:

  清单 13. 创建一个新的 TagLib

$ grails create-tag-lib Date
[copy] Copying
1 file to /src/trip-planner2/grails-app/taglib
Created TagLib
for Date
[copy] Copying
1 file to /src/trip-planner2/test/integration
Created TagLibTests
for Date

  将清单 14 中的代码添加到 DateTagLib.groovy:

  清单 14. 创建定制的 TagLib

import java.text.SimpleDateFormat

class DateTagLib {
  def customDateFormat
= {attrs, body ->
    def b
= attrs.body ?: body()
    def d
= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(b)
    
    
//if no format attribute is supplied, use this
    def pattern
= attrs["format"] ?: "MM/dd/yyyy"
    out
<< new SimpleDateFormat(pattern).format(d)
  }
}

  TagLib 接受属性形式的简单的 String 值和标记体,并将一个 String 发送到输出流。由于您将使用这个定制标记封装未格式化的 Date 字段,所以需要两个 SimpleDateFormat 对象。输入对象读入一个与 Date.toString() 调用的默认格式相匹配的 String。当将其解析为适当的 Date 对象之后,您就可以创建第二个 SimpleDateFormat 对象,以便以另一种格式的 String 将它传回。

  使用新的 TagLib 在 list.gsp 和 show.gsp 中封装 checkIn 和 checkOut 字段。如清单 15 所示:

  清单 15. 使用定制的 TagLib

<g:customDateFormat>${fieldValue(bean:hotelStay, field:'checkIn')}</g:customDateFormat>

  输入 grails run-app,然后访问 http://localhost:9090/trip/hotelStay/list,检查实际使用中的定制 TagLib,如图 13 所示:

  图 13. 使用定制 TagLib 的数据输出  

  现在,编写清单 16 中的几个测试,用来检查 TagLib 是否按照预期工作:

  清单 16. 测试定制的 TagLib

import java.text.SimpleDateFormat

class DateTagLibTests extends GroovyTestCase {
    void testNoFormat() {
      def output
=
        
new DateTagLib().customDateFormat(format:null, body:"2008-10-01 00:00:00.0")
      println
"\ncustomDateFormat using the default format:"
      println output
      
      assertEquals
"was the default format used?", "10/01/2008", output
    }

    void testCustomFormat() {
      def output
=
        
new DateTagLib().customDateFormat(format:"EEEE", body:"2008-10-01 00:00:00.0")
      assertEquals
"was the custom format used?", "Wednesday", output
    }
}
0
相关文章