From 30e8e0f23dc8dbeba5a271773fe7b4411598a8e0 Mon Sep 17 00:00:00 2001 From: islishude Date: Sat, 21 Dec 2019 00:01:59 +0800 Subject: [PATCH] Allow AssignableToTypeOf reflect.Type --- gomock/matchers.go | 6 ++++++ gomock/matchers_test.go | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/gomock/matchers.go b/gomock/matchers.go index 378c4046..4eca6206 100644 --- a/gomock/matchers.go +++ b/gomock/matchers.go @@ -194,6 +194,12 @@ func Not(x interface{}) Matcher { // var s fmt.Stringer = &bytes.Buffer{} // AssignableToTypeOf(s).Matches(time.Second) // returns true // AssignableToTypeOf(s).Matches(99) // returns false +// +// var ctx = reflect.TypeOf((*context.Context)).Elem() +// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true func AssignableToTypeOf(x interface{}) Matcher { + if xt, ok := x.(reflect.Type); ok { + return assignableToTypeOfMatcher{xt} + } return assignableToTypeOfMatcher{reflect.TypeOf(x)} } diff --git a/gomock/matchers_test.go b/gomock/matchers_test.go index 8bb87f75..47fff32b 100644 --- a/gomock/matchers_test.go +++ b/gomock/matchers_test.go @@ -17,7 +17,9 @@ package gomock_test import ( + "context" "errors" + "reflect" "testing" "github.com/golang/mock/gomock" @@ -116,4 +118,14 @@ func TestAssignableToTypeOfMatcher(t *testing.T) { if match := gomock.AssignableToTypeOf(&Dog{}).Matches(&Dog{Breed: "pug", Name: "Fido"}); !match { t.Errorf(`AssignableToTypeOf(&Dog{}) should match &Dog{Breed: "pug", Name: "Fido"}`) } + + ctxInterface := reflect.TypeOf((*context.Context)(nil)).Elem() + if match := gomock.AssignableToTypeOf(ctxInterface).Matches(context.Background()); !match { + t.Errorf(`AssignableToTypeOf(context.Context) should not match context.Background()`) + } + + ctxWithValue := context.WithValue(context.Background(), "key", "val") + if match := gomock.AssignableToTypeOf(ctxInterface).Matches(ctxWithValue); !match { + t.Errorf(`AssignableToTypeOf(context.Context) should not match ctxWithValue`) + } }