Skip to content

Commit be8372a

Browse files
Dinesh Kumarernesto-jimenez
authored andcommitted
Adding logging when mock assertions fails
1 parent a726187 commit be8372a

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

mock/mock.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,7 @@ func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool {
389389
}
390390
m := obj.(assertExpectationser)
391391
if !m.AssertExpectations(t) {
392+
t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m))
392393
return false
393394
}
394395
}

mock/mock_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package mock
33
import (
44
"errors"
55
"fmt"
6+
"regexp"
67
"sync"
78
"testing"
89
"time"
@@ -1328,6 +1329,37 @@ func (s *timer) GetTime(i int) string {
13281329
return s.Called(i).Get(0).(string)
13291330
}
13301331

1332+
type tCustomLogger struct {
1333+
*testing.T
1334+
logs []string
1335+
errs []string
1336+
}
1337+
1338+
func (tc *tCustomLogger) Logf(format string, args ...interface{}) {
1339+
tc.T.Logf(format, args...)
1340+
tc.logs = append(tc.logs, fmt.Sprintf(format, args...))
1341+
}
1342+
1343+
func (tc *tCustomLogger) Errorf(format string, args ...interface{}) {
1344+
tc.errs = append(tc.errs, fmt.Sprintf(format, args...))
1345+
}
1346+
1347+
func (tc *tCustomLogger) FailNow() {}
1348+
1349+
func TestLoggingAssertExpectations(t *testing.T) {
1350+
m := new(timer)
1351+
m.On("GetTime", 0).Return("")
1352+
tcl := &tCustomLogger{t, []string{}, []string{}}
1353+
1354+
AssertExpectationsForObjects(tcl, m, new(TestExampleImplementation))
1355+
1356+
require.Equal(t, 1, len(tcl.errs))
1357+
assert.Regexp(t, regexp.MustCompile("(?s)FAIL: 0 out of 1 expectation\\(s\\) were met.*The code you are testing needs to make 1 more call\\(s\\).*"), tcl.errs[0])
1358+
require.Equal(t, 2, len(tcl.logs))
1359+
assert.Regexp(t, regexp.MustCompile("(?s)FAIL:\tGetTime\\(int\\).*"), tcl.logs[0])
1360+
require.Equal(t, "Expectations didn't match for Mock: *mock.timer", tcl.logs[1])
1361+
}
1362+
13311363
func TestAfterTotalWaitTimeWhileExecution(t *testing.T) {
13321364
waitDuration := 1
13331365
total, waitMs := 5, time.Millisecond*time.Duration(waitDuration)

0 commit comments

Comments
 (0)