覆盖日期在Grails中进行测试 [英] Overriding dateCreated for testing in Grails
问题描述
有没有什么办法可以覆盖我的域类中的 dateCreated
字段的值而不关闭自动时间戳?
Is there any way I can override the value of dateCreated
field in my domain class without turning off auto timestamping?
我需要测试控制器,并且必须提供具体创建日期的特定域对象,但GORM似乎覆盖了我提供的值。
I need to test controller and I have to provide specific domain objects with specific creation date but GORM seems to override values I provide.
我的课程如下所示:
My classes look like this:
class Message {
String content
String title
User author
Date dateCreated
Date lastUpdated
static hasMany = [comments : Comment]
static constraints = {
content blank: false
author nullable: false
title nullable: false, blank: false
}
static mapping = {
tablePerHierarchy false
tablePerSubclass true
content type: "text"
sort dateCreated: 'desc'
}
}
class BlogMessage extends Message{
static belongsTo = [blog : Blog]
static constraints = {
blog nullable: false
}
}
我使用控制台来缩短事情。我写的时候遇到的问题是,当我写作时:
I'm using console to shorten things up. The problem which I encountered with Victor's approach is, when I write:
Date someValidDate = new Date() - (20*365)
BlogMessage.metaClass.setDateCreated = {
Date d ->
delegate.@dateCreated = someValidDate
}
我得到以下异常:
groovy.lang.MissingFieldException: No such field: dateCreated for class: pl.net.yuri.league.blog.BlogMessage
当我尝试时
Message.metaClass.setDateCreated = {
Date d ->
delegate.@dateCreated = someValidDate
}
脚本很顺利,但不幸的是 dateCreated
未被更改。
Script goes well, but unfortunately dateCreated
is not being altered.
推荐答案
我遇到类似的问题,并且能够通过
I was having a similar issue, and was able to overwrite dateCreated for my domain (in a Quartz Job test, so no @TestFor annotation on the Spec, Grails 2.1.0) by
- $ b $覆盖我的域的dateCreated(在Quartz Job测试中,所以在Spec,Grails 2.1.0上没有@TestFor注解) b
- 使用BuildTestData插件(我们经常使用它,它真是太棒了)
- 使用save(flush:true)双击域实例
- Using the BuildTestData plugin (which we use regularly anyway, it is fantastic)
- Double-tapping the domain instance with save(flush:true)
作为参考,我的测试:
For reference, my test:
import grails.buildtestdata.mixin.Build
import spock.lang.Specification
import groovy.time.TimeCategory
@Build([MyDomain])
class MyJobSpec extends Specification {
MyJob job
def setup() {
job = new MyJob()
}
void "test execute fires my service"() {
given: 'mock service'
MyService myService = Mock()
job.myService = myService
and: 'the domains required to fire the job'
Date fortyMinutesAgo
use(TimeCategory) {
fortyMinutesAgo = 40.minutes.ago
}
MyDomain myDomain = MyDomain.build(stringProperty: 'value')
myDomain.save(flush: true) // save once, let it write dateCreated as it pleases
myDomain.dateCreated = fortyMinutesAgo
myDomain.save(flush: true) // on the double tap we can now persist dateCreated changes
when: 'job is executed'
job.execute()
then: 'my service should be called'
1 * myService.someMethod()
}
}
这篇关于覆盖日期在Grails中进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!