Skip to content

Commit

Permalink
Merge pull request #37 from ovechkin-dm/36-argument-matchers-are-bein…
Browse files Browse the repository at this point in the history
…g-reused-across-mocks

Invalid matcher declaration
  • Loading branch information
ovechkin-dm authored Jan 8, 2024
2 parents 5f8c844 + 936c23b commit b50b2ff
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions registry/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ func (h *invocationHandler) VerifyMethod(verifier matchers.MethodVerifier) {
defer h.lock.Unlock()
h.ctx.getState().verifyState = true
h.ctx.getState().methodVerifier = verifier
if len(h.ctx.getState().matchers) != 0 {
h.ctx.reporter.ReportUnexpectedMatcherDeclaration(h.ctx.getState().matchers)
}
}

func (h *invocationHandler) DoVerifyMethod(call *MethodCall) []reflect.Value {
Expand Down
10 changes: 10 additions & 0 deletions registry/reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,13 @@ func (e *EnrichedReporter) ReportNoMoreInteractionsExpected(instanceType reflect
methodSig := prettyPrintMethodSignature(instanceType, call.Method.Type)
e.Errorf("no more interactions expected on %v", methodSig)
}

func (e *EnrichedReporter) ReportUnexpectedMatcherDeclaration(m []*matcherWrapper) {
sb := strings.Builder{}
sb.WriteString("Unexpected matchers declaration:\n")
for _, v := range m {
sb.WriteString(fmt.Sprintf("\t%s\n", v.matcher.Description()))
}
sb.WriteString("Matchers can only be used within When() call")
e.Errorf(sb.String())
}
2 changes: 2 additions & 0 deletions tests/check/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ func TestNonInterfaceNotAllowed(t *testing.T) {
_ = Mock[St]()
r.AssertError()
}


5 changes: 5 additions & 0 deletions tests/common/common.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package common

import (
"errors"
"fmt"
"reflect"
"strings"
Expand Down Expand Up @@ -29,6 +30,10 @@ func (m *MockReporter) GetErrorString() string {
return m.reported
}

func (m *MockReporter) GetError() error {
return errors.New(m.reported)
}

func (m *MockReporter) AssertNoError() {
if m.IsError() {
m.t.Fatalf("Expected no error, got: %s", m.reported)
Expand Down
9 changes: 9 additions & 0 deletions tests/match/match_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,12 @@ func TestDeepEqual(t *testing.T) {
result := m.Test(&s2)
r.AssertEqual(result, 9)
}

func TestUnexpectedUseOfMatchers(t *testing.T) {
r := common.NewMockReporter(t)
SetUp(r)
m := Mock[Iface]()
m.Test(AnyString())
Verify(m, Once()).Test("test")
r.AssertErrorContains(r.GetError(), "Unexpected matchers declaration")
}

0 comments on commit b50b2ff

Please sign in to comment.