How can I discard the .save () object method in an integration test?

For the integration test, I want to have .save() intentionally to check for else -condition.

My class under testing does the following:

From UserService.groovy:

 User user = User.findByXyz(xyz) if (user) { // foo if (user.save()) { // bar } else { // I WANT TO GET HERE } } 

The approaches I tried so far have failed:

What I tried 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 correctly jump to an else block from an integration test?

+4
source share
3 answers

You almost never need to mock or change the metaclass in integration tests - only unit tests.

If you want to skip the save() call, just pass data that is not checked. For example, by default, all fields are non-zero, so using def user = new User() should fail.

+3
source

Perhaps you could try modifying "validate" to be something else - using the same metaclass programs that you showed. Thus, if the verification fails, the save will certainly fail.

0
source

What I do in such cases: I always have at least one field that is not equal to zero. I just don't install it and then call .save () If you want to achieve this on an object already in the database, just load it with find or get and set one of the non-null values ​​to null, and then try to save his. If you don’t have Config.groovy configured to throw exceptions when saving fails, it will not throw an exception, it just won’t save it [you can call .validate () upfront to determine if it will save or not, and check object_instance .errors.allErrors to see errors].

0
source

All Articles