且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

覆盖日期在Grails中进行测试

更新时间:2023-09-18 11:33:28

我遇到类似的问题,并且能够通过

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()
    }
}