[英]Grails 2.2 Integration test fails when using withNewSession
我正在从grails 1.3.6迁移到2.2.4。 我目前在集成测试中使用withNewSession时遇到问题。 我已经建立了一个演示项目,以更清楚地说明问题。 下面的代码:
class DomainA {
String id
String domainB
String description
static constraints =
{
id unique: true, nullable:false
domainB (nullable: false, blank:false,
validator:{val, obj ->
if(val != null)
{
DomainA.withNewSession{session ->
def result = DomainB.findByDescription(val)
if(result == null)
{
return 'foreignkey'
}
}
}
})
}
static mapping =
{
table 'DOMAIN_A'
id column:'id', type: 'string', generator: 'assigned'
version false
domainB column:'DOMAIN_B'
}
}
class DomainB {
String id
String description
static constraints =
{
id unique: true, nullable:false
description nullable:false
}
static mapping =
{
table 'DOMAIN_B'
id column:'id', type: 'string', generator: 'assigned'
version false
}
}
和整合测试
import static org.junit.Assert.*
import org.junit.*
class WithNewSessionTestTests extends GroovyTestCase{
@Before
void setUp() {
DomainB b = new DomainB(description:"BEE")
b.id = "B"
b.save(flush:true, failOnError:true)
DomainA a = new DomainA(domainB:"BEE", description:"EHH")
a.id = "A"
a.save(flush:true, failOnError:true)
}
@Test
void testSomething() {
assertTrue true
}
}
在测试失败时a
试图保存。 返回的错误代码是'foreignkey',这是DomainA
找不到DomainB
实例时返回的内容。 调试还向我显示DomainB.findByDescription(val)
的结果值为null
。 关于如何解决这个问题的任何想法? 我希望我的测试继续对avo有用
如果我从验证中删除withNewSession
或将测试设置为static transactional = false
则此测试将成功。 关于如何保留withNewSession调用和测试的事务性质的任何想法?
版本:Grails 2.2.4,Oracle 10 +,Java 7.0.21,groovy 2.0.7
更改
class DomainA {
String id
String domainB
String description
----- rest of the code
}
至
class DomainA {
String id
DomainB domainB
String description
}
在集成测试中
import static org.junit.Assert.*
import org.junit.*
class WithNewSessionTestTests extends GroovyTestCase{
@Before
void setUp() {
DomainB b = new DomainB(description:"BEE")
b.id = "B"
b.save(flush:true, failOnError:true)
DomainA a = new DomainA(domainB:b, description:"EHH")
a.id = "A"
a.save(flush:true, failOnError:true)
}
@Test
void testSomething() {
assertTrue true
}
}
这应该工作。
编辑
集成测试默认情况下在数据库事务中运行,该事务将在每个测试结束时回滚。 这意味着测试期间保存的数据不会持久保存到数据库中。 将事务性属性添加到测试类中以检查事务性行为:
class MyServiceTests extends GroovyTestCase {
static transactional = false
void testMyTransactionalServiceMethod() {
…
} }
确保从非事务测试中删除任何持久化的数据,例如在tearDown方法中,这样这些测试不会干扰期望干净数据库的标准事务测试。
如果没有static transactional = false
则测试将不得不持久化到db,而在集成测试中,数据将回滚而不是持久化到数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.