mock: Conditionally toggle mock Call #1605
Open
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Toggle on/off Unset method with an option.
Changes
UnsetOption
was definedUnsetOption
were defined:WithUnsetToggle
,WithUnsetEnabled
,WithUnsetDisabled
Unset
method will accept variadic list ofUnsetOptions
to be called, which makes the new change entirely backward-compatibleUnset
will be enabled, which is also backward-compatibleMotivation
Consider the following example test scenario:
The goal is to test http server API. The test may set up a local http server, database and mocks to 3rd party services. Since the tests are calling a mocked server, it may be useful to use mock
EXPECT()
calls. Test structure:As an enhancement, such tests can easily be called against deployed application, by simply replacing server and database URLs. The only catch are mocked calls, which won't be executed, since the request is sent to a remote server.
In such case, it may be possible to call
Unset()
method withWithUnsetToggle
option, which value is set based on the current environment. For example:In the above example, if environment is "local" Unset will be disabled, meaning that all mocks will execute.
If environment is other than "local" the Unset will be enabled, meaning that mocks will not be called.
This allows to run the same suite of tests regardless of environment and setup.
Alternative approach
P.S. If there is an easier way to achieve similar behaviour than what I proposed, please let me know. I wasn't able to find any workaround, other than calling
Unset
inif
block. I am also open to any suggestions and would definitely like to implement this logic somewhere in testify package, only if you think this is the right approach.Related issues
None