Overriding dateCreated for testing in Grails

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

    As of grails 2.5.1, getMapping() method of GrailsDomainBinder class is not static,non of the above method works as is. However, @Volt0's method works with minor tweaking. Since all of us are trying to do so to make our tests working, instead of placing it in BootStrap, I placed it in actual integration test. Here is my tweak to Volt0's method:

    def disableAutoTimestamp(Class domainClass) {
        Mapping mapping = new GrailsDomainBinder().getMapping(domainClass)
        mapping.autoTimestamp = false
    }
    
    def enableAutoTimestamp(Class domainClass) {
        Mapping mapping = new GrailsDomainBinder().getMapping(domainClass)
        mapping.autoTimestamp = true
    }
    

    And simply call these methods in tests like

    disableAutoTimestamp(Domain.class)
    //Your DB calls
    enableAutoTimestamp(Domain.class)
    

    The above code can also be placed in src directory and can be called in tests however I placed this in actual test as there was only one class in my app where I needed this.

提交回复
热议问题