Skip to content

Commit

Permalink
improve find expected call
Browse files Browse the repository at this point in the history
  • Loading branch information
everdance authored and glesica committed Jul 12, 2019
1 parent 555ebd3 commit 1bb3d5a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
19 changes: 13 additions & 6 deletions mock/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,17 +262,21 @@ func (m *Mock) On(methodName string, arguments ...interface{}) *Call {
// */

func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) {
for i, call := range m.ExpectedCalls {
if call.Method == method && call.Repeatability > -1 {
var expectedCall *Call

for i, call := range m.ExpectedCalls {
if call.Method == method {
_, diffCount := call.Arguments.Diff(arguments)
if diffCount == 0 {
return i, call
expectedCall = call
if call.Repeatability > -1 {
return i, call
}
}

}
}
return -1, nil

return -1, expectedCall
}

func (m *Mock) findClosestCall(method string, arguments ...interface{}) (*Call, string) {
Expand Down Expand Up @@ -344,13 +348,16 @@ func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Argumen
found, call := m.findExpectedCall(methodName, arguments...)

if found < 0 {
// expected call found but it has already been called with repeatable times
if call != nil {
m.fail("\nassert: mock: The method has been called over %d times.\n\tEither do one more Mock.On(\"%s\").Return(...), or remove extra call.\n\tThis call was unexpected:\n\t\t%s\n\tat: %s", call.totalCalls, methodName, callString(methodName, arguments, true), assert.CallerInfo())
}
// we have to fail here - because we don't know what to do
// as the return arguments. This is because:
//
// a) this is a totally unexpected call to this method,
// b) the arguments are not what was expected, or
// c) the developer has forgotten to add an accompanying On...Return pair.

closestCall, mismatch := m.findClosestCall(methodName, arguments...)
m.mutex.Unlock()

Expand Down
10 changes: 10 additions & 0 deletions mock/mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,16 @@ func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) {
}
}

c = m.On("Once", 1).Return("one").Once()
c.Repeatability = -1
f, c = m.findExpectedCall("Once", 1)
if assert.Equal(t, -1, f) {
if assert.NotNil(t, c) {
assert.Equal(t, "Once", c.Method)
assert.Equal(t, 1, c.Arguments[0])
assert.Equal(t, "one", c.ReturnArguments[0])
}
}
}

func Test_callString(t *testing.T) {
Expand Down

0 comments on commit 1bb3d5a

Please sign in to comment.