1

我有一个 Grails 2.2.4 项目,我正在尝试为查询 over 的方法编写单元测试lastUpdated,如下所示:

Tile.createCriteria().list {
  lt('lastUpdated', new Date() - 1)
}

这种方法在现实生活中工作得很好,但在我的单元测试中失败了,因为我不能lastUpdatednow. 显式设置myTile.lastUpdated不起作用,因为这是一个更新,因此会触发自动时间戳。关闭自动时间戳需要eventTriggeringInterceptor,这在单元测试中似乎不可用。模拟默认Date构造函数以返回其他值也无济于事。直接 SQL 更新在单元测试中根本不可用。

这在单元测试中是否可能,还是我必须编写集成测试?

4

1 回答 1

1

有趣的是,您说模拟默认日期构造函数以返回其他值没有帮助。当我有像你这样的新约会时,我经常成功地做到这一点。对于您的情况,我会有一个看起来像这样的单元测试:

def 'test lastUpdated query'() {
    setup:
    Title lessThan = new Title(lastUpdated:new Date(1477152000000)) //22 Oct 2016 16:00 UTC, should be found
    Title equalTo = new Title(lastUpdated:new Date(1477238400000)) //24 Oct 2016 16:00 UTC, should not find, not less than 1 day before, but equal to 1 day before
    Title notLessThan = new Title(lastUpdated:new Date(1477296000000)) //24 Oct 2016 08:00 UTC, should not find, not less than 1 day before
    Date date = new Date(1477324800000) //24 Oct 2016 16:00 UTC
    Date.metaClass.constructor = {-> return date}

    when:
    List<Title> result = service.someMethod()

    then:
    result.size() == 1
    result.contains(lessThan)
    !result.contains(equalTo)
    !result.contains(notLessThan)
}
于 2016-10-24T15:57:06.960 回答