Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Commit

Permalink
MOCK-429: add support for assignable types to Eq matcher (#481)
Browse files Browse the repository at this point in the history
  • Loading branch information
GrigoriyMikhalkin committed Oct 23, 2020
1 parent eb4f989 commit 69e02d3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
16 changes: 15 additions & 1 deletion gomock/matchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,21 @@ type eqMatcher struct {
}

func (e eqMatcher) Matches(x interface{}) bool {
return reflect.DeepEqual(e.x, x)
// In case, some value is nil
if e.x == nil || x == nil {
return reflect.DeepEqual(e.x, x)
}

// Check if types assignable and convert them to common type
x1Val := reflect.ValueOf(e.x)
x2Val := reflect.ValueOf(x)

if x1Val.Type().AssignableTo(x2Val.Type()) {
x1ValConverted := x1Val.Convert(x2Val.Type())
return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface())
}

return false
}

func (e eqMatcher) String() string {
Expand Down
6 changes: 6 additions & 0 deletions gomock/matchers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import (
"github.com/golang/mock/gomock/internal/mock_gomock"
)

type A []string

func TestMatchers(t *testing.T) {
type e interface{}
tests := []struct {
Expand All @@ -44,6 +46,10 @@ func TestMatchers(t *testing.T) {
[]e{[]int{1, 2}, "ab", map[string]int{"a": 0, "b": 1}, [2]string{"a", "b"}},
[]e{[]int{1}, "a", 42, 42.0, false, [1]string{"a"}},
},
{"test assignable types", gomock.Eq(A{"a", "b"}),
[]e{[]string{"a", "b"}, A{"a", "b"}},
[]e{[]string{"a"}, A{"b"}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit 69e02d3

Please sign in to comment.