Overriding dateCreated for testing in Grails

后端 未结 10 1398
日久生厌
日久生厌 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:25

    I'm using something like this for an initial import/migration.

    Taking gabe's post as a starter (which didn't work for me Grails 2.0), and looking at the old source code for ClosureEventTriggeringInterceptor in Grails 1.3.7, I came up with this:

    class BootStrap {
    
        private void changeTimestamping(Object domainObjectInstance, boolean shouldTimestamp) {
            Mapping m = GrailsDomainBinder.getMapping(domainObjectInstance.getClass())
            m.autoTimestamp = shouldTimestamp
        }
    
        def init = { servletContext ->
    
            changeTimestamping(new Message(), false)
    
            def fooMessage = new Message()
            fooMessage.dateCreated = new Date("11/5/1955")
            fooMessage.lastUpdated = new Date()
            fooMessage.save(failOnError, true)
    
            changeTimestamping(new Message(), true)
        }
    }
    

提交回复
热议问题