技术开发 频道

精通 Grails: 测试 Grails 应用程序

  创建和测试定制验证

  现在,应该处理下一个用户场景了。您需要确保 checkOut 日期发生在 checkIn 日期之后。要解决这个问题,您需要编写一个定制验证。编写完之后,要验证它。

  将清单 11 中的定制验证代码添加到 static constraints 块:

  清单 11. 一个定制的验证

class HotelStay {
  static constraints
= {
    hotel(blank:
false)
    checkIn()
    checkOut(validator:{val, obj
->
      return val.after(obj.checkIn)
    })
  }
  
  
//the rest of the class remains the same
}

  val 变量是当前的字段。obj 变量表示当前的 HotelStay 实例。Groovy 将 before() 和 after() 方法添加到所有 Date 对象,所以这个验证仅返回 after() 方法调用的结果。如果 checkOut 发生在 checkIn 之后,验证返回 true。否则,它返回 false 并触发一个错误。

  现在,输入 grails run-app。确保不能创建一个 checkOut 日期早于 checkIn 日期的新 HotelStay 实例。如图 10 所示:

  图 10. 默认的定制验证错误消息  

  打开 grails-app/i18n/messages.properties,并向 checkOut 字段添加一个定制验证消息:hotelStay.checkOut.validator.invalid=Sorry, you cannot check out before you check in。

  保存 messages.properties 文件并尝试保存有缺陷的 HotelStay。您将看到如清单 11 所示的错误消息:

  清单 11. 定制验证错误消息  

  现在应该编写测试了,如清单 12 所示:

  清单 12. 测试定制的验证

import java.text.SimpleDateFormat
class HotelStayTests extends GroovyTestCase {
  void testCheckOutIsNotBeforeCheckIn(){
    def h
= new HotelStay(hotel:"Radisson")
    def df
= new SimpleDateFormat("MM/dd/yyyy")
    h.checkIn
= df.parse("10/15/2008")
    h.checkOut
= df.parse("10/10/2008")
  
    assertFalse
"there should be errors", h.validate()
    def badField
= h.errors.getFieldError('checkOut')
    assertNotNull "I'm expecting to find an error on the checkOut field", badField
    def code
= badField?.codes.find {it == 'hotelStay.checkOut.validator.invalid'}
    assertNotNull "the checkOut field should be the culprit", code                
  }
}
0
相关文章