Overriding dateCreated for testing in Grails

后端 未结 10 1399
日久生厌
日久生厌 2021-02-12 12:27

Is there any way I can override the value of dateCreated field in my domain class without turning off auto timestamping?

I need to test controller and I ha

10条回答
  •  情深已故
    2021-02-12 13:16

    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

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

提交回复
热议问题