Skip to content

Commit

Permalink
custom matcher as function
Browse files Browse the repository at this point in the history
  • Loading branch information
ovechkin-dm committed Sep 10, 2024
1 parent 9f0f1dd commit ff280dd
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 14 deletions.
2 changes: 1 addition & 1 deletion docs/features/matchers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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''")
}
Expand Down
18 changes: 7 additions & 11 deletions mock/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions tests/match/match_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit ff280dd

Please sign in to comment.