简体   繁体   English

如何让域对象的 .save() 方法在集成测试中失败?

[英]How can I have a domain object's .save() method fail in an integration test?

For an integration test, I want to have a .save() intentionally in order to test the according else -condition.对于集成测试,我想有意使用.save()以测试相应的else条件。

My class under test does this:我正在测试的 class 这样做:

From UserService.groovy:来自 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:我在 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?如何正确地从集成测试中进入 else 块?

You should almost never have a need for mocking or altering the metaclass in integration tests - only unit tests.您几乎不需要 mocking 或在集成测试中更改元类 - 只有单元测试。

If you want to fail the save() call just pass in data that doesn't validate.如果您想使save()调用失败,只需传入未验证的数据即可。 For example all fields are not-null by default, so using def user = new User() should fail.例如,默认情况下所有字段都不为空,因此使用def user = new User()应该会失败。

maybe you could try changing the 'validate' to be something else - by using the same meta class programming that u have shown.也许您可以尝试将“验证”更改为其他内容 - 通过使用您展示的相同元 class 编程。 That way, if the validate fails, the save will certainly fail这样,如果验证失败,保存肯定会失败

What I do in such cases: I always have at least one field which is not null.在这种情况下我会做什么:我总是至少有一个字段不是 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.我根本不设置它,然后调用.save() 如果你想在数据库中已经存在的 object 上实现这一点,只需使用 find 或 get 加载它并将非 null 值之一设置为 Z37A6259CC0C1DAE298A786648 然后尝试保存它。 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].如果您没有配置 Config.groovy 以在保存时在失败时抛出异常它不会抛出异常,它根本不会保存它[您可以预先调用.validate()以确定它是否会保存并检查object_instance.errors.allErrors 列表以查看错误]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM