testify
testify copied to clipboard
Feature request: expose mock method called counter or reset it
Senario:
Application implements some caching mechanism. I want to write test cases to test that if no cache exists, the mocked third-party service is called; if cached, the mocked service will not be called.
Feature request suggestion:
mock.Mock provides AssertCalled, AssertNumberOfCalls and AssertNotCalled methods, but if multiple test cases in one test suite calls the same mocking method,AssertNotCalled will fail no matter where the mocked method is called; number of calls is nearly impossible to know so AssertNumberOfCalls can not be used.
If mock.Mock can expose called times or allow reset call counter. On cache hit, AssertNotCalled can be used to check if mocking is not called, or using AssertNumberOfCalls to check if called counter does not increase.
First of all, +1 on that. I'm looking for the same.
Second, you can reset the call counter in a hacky way by overwriting the Calls member of the mock object. It is hacky because mock.Mock is using a mutex when accessing it's members but that is not exported. So you are circumventing the locking at this point.
Looks like this:
type MyMockObject struct {
mock.Mock
}
func (m *MyMockObject) ResetCalls() {
// This is not safe! mock.Mock is using a mutex when accessing Calls.
m.Calls = []mock.Call{}
}
Any plans for this feature to be implemented?
Just scope your generated mock correctly in your tests - in that way you don't need to worry about resetting it.