Open piotrpersona opened 4 months ago
calling
Unset
inif
block
Please, just do that, it is far more readable. Better yet, inverse the logic of the if block and never set the expectation in the first place:
// less good
m := mock.Call3rdParty(ctx, argument).Return(nil)
if os.Getenv("local") {
m.Unset()
}
// better
if !os.Getenv("local") {
mock.Call3rdParty(ctx, argument).Return(nil).Once()
}
It is my opinion that Unset should not have been added to begin with, its use makes it difficult to grok what expectations a test actually has. I would urge us to not complicate it further, sorry.
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