8

GORMが自動的に管理するフィールドを含むいくつかのGrails2.1ドメインクラスがdateCreatedあります。例:lastUpdated

class Person {
    Date dateCreated
    Date lastUpdated
    String name
}

Grailsが実行時にこれらのフィールドに自動的に入力するようにしたいのですが、これらの日付の値を手動で定義できるテストデータ作成したいと思います。問題は、私が特別に設定した場合でも、これらのフィールドにインターセプターがあれば、Grailsが自動的に値を設定することです。

への変更を許可する方法を説明するこのSOの質問を見ましdateCreatedたが、私も変更する必要がありlastUpdatedます。これは可能ですか?

4

2 に答える 2

16

おっと、私の間違いです。他の質問のアプローチは機能しますが、問題のエンティティは別の場所に個別に保存されていました。また、flush物事を機能させるには明示的なものが必要なようです:

def withAutoTimestampSuppression(entity, closure) {
    toggleAutoTimestamp(entity, false)
    def result = closure()
    toggleAutoTimestamp(entity, true)
    result
}

def toggleAutoTimestamp(target, enabled) {
    def applicationContext = (ServletContextHolder.getServletContext()                                                           
                              .getAttribute(ApplicationAttributes.APPLICATION_CONTEXT))

    def closureInterceptor = applicationContext.getBean("eventTriggeringInterceptor")
    def datastore = closureInterceptor.datastores.values().iterator().next()
    def interceptor = datastore.getEventTriggeringInterceptor()

    def listener = interceptor.findEventListener(target)
    listener.shouldTimestamp = enabled
    null
}

def createTestPerson() {

    def luke = new Person(name: "Luke Skywalker")
    withAutoTimestampSuppression(luke) {

        def lastWeek = new Date().minus(7)
        luke.dateCreated = lastWeek
        luke.lastUpdated = lastWeek
        luke.save(failOnError: true, flush: true)
    }
}
于 2012-11-22T17:08:21.580 に答える
3

統合テストの場合は、hql update ステートメントを使用して、lastUpdated を手動で設定できます。

于 2014-05-22T21:53:49.797 に答える