Reputation: 2459
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?
Upvotes: 4
Views: 1224
Reputation: 3423
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].
Upvotes: 0
Reputation: 75671
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.
Upvotes: 3
Reputation: 3529
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
Upvotes: 0