如何让域对象的 .save() 方法在集成测试中失败?
对于集成测试,我希望有意使用 .save()
来测试相应的 else
条件。
我的测试类执行以下操作:
来自 UserService.groovy:
User user = User.findByXyz(xyz)
if (user) {
// foo
if (user.save()) {
// bar
} else {
// I WANT TO GET HERE
}
}
到目前为止我尝试过的方法失败了:
我在 UserServiceTests.groovy 中尝试过的内容:
def uControl = mockFor(User)
uControl.demand.save { flush -> null } // in order to test a failing user.save()
def enabledUser = userService.enableUser(u.confirmationToken)
uControl.verify()
// or the following:
User.metaClass.'static'.save = { flush -> null } // fails *all* other tests too
如何正确从集成测试到达 else-块?
For an integration test, I want to have a .save()
intentionally in order to test the according else
-condition.
My class under test does this:
From UserService.groovy:
User user = User.findByXyz(xyz)
if (user) {
// foo
if (user.save()) {
// bar
} else {
// I WANT TO GET HERE
}
}
The approaches I've tried so far failed:
What I've tried in in UserServiceTests.groovy:
def uControl = mockFor(User)
uControl.demand.save { flush -> null } // in order to test a failing user.save()
def enabledUser = userService.enableUser(u.confirmationToken)
uControl.verify()
// or the following:
User.metaClass.'static'.save = { flush -> null } // fails *all* other tests too
How can I get to the else-block from an integration test correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您几乎不需要在集成测试中模拟或更改元类 - 仅单元测试。
如果您想让
save()
调用失败,只需传入未验证的数据即可。例如,默认情况下所有字段都不为空,因此使用def user = new User()
应该会失败。You should almost never have a need for mocking or altering the metaclass in integration tests - only unit tests.
If you want to fail the
save()
call just pass in data that doesn't validate. For example all fields are not-null by default, so usingdef user = new User()
should fail.也许您可以尝试将“验证”更改为其他内容 - 通过使用您所展示的相同元类编程。
这样的话,如果验证失败,那么保存也一定会失败
maybe you could try changing the 'validate' to be something else - by using the same meta class programming that u have shown .
That way, if the validate fails, the save will certainly fail
在这种情况下我会做什么:
我总是至少有一个字段不为空。
我只是不设置它然后调用 .save()
如果您想在数据库中已有的对象上实现此目的,只需使用 find 或 get 加载它并将其中一个非空值设置为 null,然后尝试保存它。
如果您没有将 Config.groovy 配置为在保存失败时抛出异常,它将不会抛出异常,它根本不会保存它[您可以预先调用 .validate() 来确定它是否会保存并检查object_instance.errors.allErrors 列表可查看错误]。
What I do in such cases:
I always have at least one field which is not null.
I simply don't set it and then call .save()
If you want to achieve this on an object already in the database, just load it using find or get and set one of the not null values to null and then try to save it.
If you don't have Config.groovy configured to throw exceptions on failures when saving it will not throw the exception, it simply won't save it [you can call .validate() upfront to determine whether it will save or not and check object_instance.errors.allErrors list to see the errors].