我有一个应该创建域对象的方法。但是,如果在构建对象的过程中发生条件,则该方法应仅返回而不保存对象。
鉴于:
class SomeDomainObjectClass {
String name
}
class DomCreatorService {
def createDom() {
SomeDomainObjectClass obj = new SomeDomainObjectClass(name: "name")
// do some processing here and realise we don't want to save the object to the database
if (!dontWannaSave) {
obj.save(flush: true)
}
}
}
在我的测试中(服务是DomCreatorService的实例):
expect: "it doesn't exist at first"
SomeDomainObjectClass.findByName("name") == null
when: "we attempt to create the object under conditions that mean it shouldn't be saved"
// assume that my test conditions will mean dontWannaSave == true and we shouldn't save
service.createDom()
then: "we shouldn't be able to find it and it shouldn't exist in the database"
// check that we still haven't created an instance
SomeDomainObjectClass.findByName("name") == null
我的最后一行失败了。为什么最后一个findByName返回true,即为什么可以找到我的对象?我以为它只会找到保存到数据库的对象。我应该测试什么以查看是否尚未创建对象?
您必须遗漏一些东西-如果您仅创建一个实例但不对其调用任何GORM方法,则Hibernate无法知道它。它开始管理对象的唯一方法是通过初始save()
调用将其“附加” 。没有它,就像其他任何对象一样。
您会看到@agusluc所描述的内容,但这对您没有影响。如果加载以前保留的实例并修改任何属性,则在请求结束时,Hibernate的脏检查将启动,检测到此已附加但未保存的实例是脏的,即使您不进行更改,它也会将更改推送到数据库打电话save()
。在这种情况下,如果您不想继续进行修改,请通过调用将该对象从会话中分离出来discard()
。这与您看到的内容无关,因为您没有附加任何内容。
可能已经有具有该name
属性的实例。检查findByName
查询返回的其他属性,我假设您将看到它是先前持久的实例。
另外,这是单元测试还是集成?确保使用集成测试来实现持久性-单元测试模拟不适用于测试域类,它仅应用于在测试其他类型的类(例如控制器)时为域类赋予GORM行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句