Skip to content

fix(mock): allow Unset() on calls with type matchers - #2015

Open
Yshuro wants to merge 1 commit into
stretchr:masterfrom
Yshuro:fix/issue-1599
Open

Yshuro wants to merge 1 commit into
stretchr:masterfrom
Yshuro:fix/issue-1599

Conversation

@Yshuro

@Yshuro Yshuro commented Nov 21, 2026

Copy link
Copy Markdown

Summary

Fix Call.Unset() panics when called on mock expectations configured with type matchers or custom matchers (mock.AnythingOfType, mock.IsType, mock.MatchedBy).

Changes

  • In (*Call).Unset(), check pointer equality (call == c) when filtering ExpectedCalls, ensuring the targeted expectation call itself is properly recognized and removed even when it contains complex matchers like mock.MatchedBy.
  • In (Arguments).Diff(), handle �nythingOfTypeArgument and *IsTypeArgument when �ctual is also of the respective matcher type, allowing Unset() by method specification to match existing calls configured with type matchers.
  • Add unit tests in mock/mock_test.go covering Unset() with AnythingOfType, IsType, and MatchedBy, as well as unsetting by method spec with AnythingOfType.

Motivation

Calling call.Unset() on an expectation configured with mock.AnythingOfType or other matchers previously panicked because Arguments.Diff() treated matcher arguments as concrete values and failed type checks against themselves, causing Unset() to report that the expected call could not be found.

Related issues

Closes #1599

Signed-off-by: Yshuro <yshuro1080@gmail.com>

@atishay-kasliwal atishay-kasliwal left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran Unset() on calls set up with AnythingOfType, Anything, MatchedBy and nil. Master panicked on all but Anything; here each removes only its own call.

Comment thread mock/mock.go
// in-place filter slice for calls to be removed - iterate from 0'th to last skipping unnecessary ones
var index int // write index
for _, call := range c.Parent.ExpectedCalls {
if call == c {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With two identical expectations (On("F", 1).Once() then On("F", 1)), unsetting the second still removes both, because the argument match below also runs, same as on master. Now that the pointer check is here, is the argument match still needed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

call.Unset() panics when call := mockObj.On("Foo", mock.AnythingOfType("foo"))

2 participants