gpt4 book ai didi

grails - 覆盖日期创建用于Grails中的测试

转载 作者:行者123 更新时间:2023-12-03 12:44:54 25 4
gpt4 key购买 nike

有什么方法可以在不关闭自动时间戳的情况下覆盖域类中dateCreated字段的值?

我需要测试 Controller ,并且必须提供具有特定创建日期的特定域对象,但GORM似乎会覆盖我提供的值。

编辑

我的类(class)如下:

class Message {

String content
String title
User author

Date dateCreated
Date lastUpdated

static hasMany = [comments : Comment]

static constraints = {
content blank: false
author nullable: false
title nullable: false, blank: false
}

static mapping = {
tablePerHierarchy false
tablePerSubclass true
content type: "text"
sort dateCreated: 'desc'
}
}

class BlogMessage extends Message{

static belongsTo = [blog : Blog]

static constraints = {
blog nullable: false
}

}

我正在使用控制台来缩短时间。我在写Victor的方法时遇到的问题是:
Date someValidDate = new Date() - (20*365)

BlogMessage.metaClass.setDateCreated = {
Date d ->
delegate.@dateCreated = someValidDate
}

我得到以下异常:
groovy.lang.MissingFieldException: No such field: dateCreated for class: pl.net.yuri.league.blog.BlogMessage

当我尝试
Message.metaClass.setDateCreated = {
Date d ->
delegate.@dateCreated = someValidDate
}

脚本运行良好,但不幸的是 dateCreated未被更改。

最佳答案

我遇到了类似的问题,并且能够通过以下方式覆盖为我的域创建的dateCreate(在Quartz Job测试中,因此Spec上没有@TestFor注释,Grails 2.1.0)

  • 使用BuildTestData插件(无论如何我们都经常使用,这太棒了)
  • 使用save(flush:true)双击域实例

  • 供引用,我的测试:
    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()
    }
    }

    关于grails - 覆盖日期创建用于Grails中的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5733448/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com