Overriding dateCreated for testing in Grails

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

    As of Grails 3 and GORM 6 you can tap into AutoTimestampEventListener to execute a Runnable that temporarily ignores all or select timestamps.

    The following is a small snippet I use in my integration tests where this is necessary:

    void executeWithoutTimestamps(Class domainClass, Closure closure){
        ApplicationContext applicationContext = Holders.findApplicationContext()
        HibernateDatastore mainBean = applicationContext.getBean(HibernateDatastore)
        AutoTimestampEventListener listener = mainBean.getAutoTimestampEventListener()
    
        listener.withoutTimestamps(domainClass, closure)
    }
    

    Then in your case you could do the following:

    executeWithoutTimestamps(BlogMessage, {
        Date someValidDate = new Date() - (20*365)
        BlogMessage message = new BlogMessage()
        message.dateCreated = someValidDate
        message.save(flush: true)
    })
    

提交回复
热议问题