简体   繁体   中英

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.

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?

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 using def 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

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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