grails,单元测试具有指定id的模拟域

iMi*_*MiX 8 grails groovy unit-testing grails-orm

我在我的域中使用已分配的ID

class Book {

Integer id
String name

static mapping = {
    id generator: 'assigned'
    }   
}
Run Code Online (Sandbox Code Playgroud)

所以要添加一本新书:

def book = new Book([name: "The Adventures of Huckleberry Finn"])
book.id = 123
book.save(flush: true)
Run Code Online (Sandbox Code Playgroud)

一切都很完美,问题出在我的单元测试中

首先我只能嘲笑1域类,其次,我不能在单元测试使用.save(),所以我唯一的选择(据我所知)是使用mockDomain如下:

mockDomain(Book, [ [id: 123, name: "The Adventures of Huckleberry Finn"] ])
Run Code Online (Sandbox Code Playgroud)

但它不起作用,它将在没有"id generator:'assigned'"的普通域中工作

有任何想法吗?我读到在集成测试中我不会遇到这个问题,这只是单元测试中的问题谢谢

dma*_*tro 9

如果要使用(默认情况下不是)它作为map params来在单元测试中创建域对象,则需要bindable约束.域类会有ididbindable

static constraints = {
    id bindable: true
}
Run Code Online (Sandbox Code Playgroud)

建议:
如果您使用的是Grails> 2.x,请使用@Mock模拟域类而不是mockDomain.您可以在Grails文档中找到有关单元测试的详细信息.

另一个Level Up
Use build-test-data插件用于模拟域对象.