我正在尝试将fixture 和 build-test-data 合并到我们的 grails 测试中,但即使是最简单的示例,在尝试使用 build-test-data 插件构建两个相同的类时,我也会遇到 id 冲突。我不禁觉得我错过了一些非常简单的东西。
这工作得很好。假设需要导入的所有内容都已导入。
class TemporaryFixturesTests extends GroovyTestCase {
/* injected */
def fixtureLoader
void testFixtureLoadsProperly() {
def fixture = fixtureLoader.load {
build {
testCompany(Company, name: "TestCompany")
testBasicUser(User, username: "TestUserBasic", company: testCompany)
}
}
assert fixture.testBasicUser.company.name == "TestCompany"
}
void setUp() {
//TODO
}
}
然而这一...
class TemporaryFixturesTests extends GroovyTestCase {
/* injected */
def fixtureLoader
void testFixtureLoadsProperly() {
def fixture = fixtureLoader.load {
build {
testCompany(Company, name: "TestCompany")
testCompany2(Company, name: "TestCompany2")
testBasicUser(User, username: "TestUserBasic", company: testCompany)
testBasicUser2(User, username: "TestUserBasic2", company: testCompany2)
}
}
assert fixture.testBasicUser.company.name == "TestCompany"
assert fixture.testBasicUser2.company.name == "TestCompany2"
}
void setUp() {
//TODO
}
}
打破错误...
nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [<path removed>.Company#0]
这让我相信 build-test-data 试图将 id0 与两家公司相关联。臭死了。谁能告诉我为什么?
- 编辑 -
似乎有问题的表没有设置为具有自动递增的 ID。因此,当构建测试数据试图让我成为一个 id 列时,它每次都会生成 0,因为这是一个自动生成的整数。
osborp 为此提供了解决方案。构建一个 TestDataConfig :
测试数据配置 {
sampleData {
'<path removed>.Company' {
def i = 0
id = {-> i++ }
}
'<path removed>.User' {
def i = 0
id = {-> i++ }
}
}
}