From ff280dd1e48e3395f30134112a5c2fe846d71cf4 Mon Sep 17 00:00:00 2001 From: ovechkin-dm Date: Tue, 10 Sep 2024 12:05:20 +0200 Subject: [PATCH] custom matcher as function --- docs/features/matchers.md | 2 +- mock/api.go | 18 +++++++----------- tests/match/match_test.go | 4 ++-- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/docs/features/matchers.md b/docs/features/matchers.md index 41fd0f6..2d677e8 100644 --- a/docs/features/matchers.md +++ b/docs/features/matchers.md @@ -449,7 +449,7 @@ func TestSimple(t *testing.T) { odd := CreateMatcher[int]("odd", func(args []any, v int) bool { return v%2 == 1 }) - When(greeter.Greet(Match(odd))).ThenReturn("hello odd number") + When(greeter.Greet(odd())).ThenReturn("hello odd number") if greeter.Greet(1) != "hello odd number" { t.Error("expected ''hello odd number''") } diff --git a/mock/api.go b/mock/api.go index aa66f0c..897d6af 100644 --- a/mock/api.go +++ b/mock/api.go @@ -376,17 +376,13 @@ func OneOf[T any](values ...T) T { // CreateMatcher returns a Matcher that matches values of type T using the provided Matcher implementation. // The provided Matcher implementation must implement the Matcher interface. -func CreateMatcher[T any](description string, f func(allArgs []any, actual T) bool) matchers.Matcher[T] { - m := registry.FunMatcher[T](description, f) - return m -} - -// Match provides matching for method argument with a matcher that was created via CreateMatcher -// The provided Matcher implementation must implement the Matcher interface. -func Match[T any](m matchers.Matcher[T]) T { - registry.AddMatcher(m) - var t T - return t +func CreateMatcher[T any](description string, f func(allArgs []any, actual T) bool) func() T { + return func() T { + m := registry.FunMatcher[T](description, f) + registry.AddMatcher(m) + var t T + return t + } } // WhenSingle takes an argument of type T and returns a ReturnerSingle interface diff --git a/tests/match/match_test.go b/tests/match/match_test.go index 1209ff2..f6196dd 100644 --- a/tests/match/match_test.go +++ b/tests/match/match_test.go @@ -110,11 +110,11 @@ func TestNonEqualStruct(t *testing.T) { func TestCustomMatcher(t *testing.T) { r := common.NewMockReporter(t) SetUp(r) - evenm := CreateMatcher[int]("even", func(allArgs []any, actual int) bool { + even := CreateMatcher[int]("even", func(allArgs []any, actual int) bool { return actual%2 == 0 }) m := Mock[Iface]() - WhenSingle(m.Test(Match(evenm))).ThenReturn(true) + WhenSingle(m.Test(even())).ThenReturn(true) ret1 := m.Test(10) ret2 := m.Test(11) r.AssertEqual(ret1, true)