From be8372ae8ec5c6daaed3cc28ebf73c54b737c240 Mon Sep 17 00:00:00 2001 From: Dinesh Kumar Date: Fri, 2 Feb 2018 21:05:43 +0530 Subject: [PATCH] Adding logging when mock assertions fails --- mock/mock.go | 1 + mock/mock_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/mock/mock.go b/mock/mock.go index 55c49ea51..e150c6dd4 100644 --- a/mock/mock.go +++ b/mock/mock.go @@ -389,6 +389,7 @@ func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { } m := obj.(assertExpectationser) if !m.AssertExpectations(t) { + t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) return false } } diff --git a/mock/mock_test.go b/mock/mock_test.go index 1d7101e43..b433e7af6 100644 --- a/mock/mock_test.go +++ b/mock/mock_test.go @@ -3,6 +3,7 @@ package mock import ( "errors" "fmt" + "regexp" "sync" "testing" "time" @@ -1328,6 +1329,37 @@ func (s *timer) GetTime(i int) string { return s.Called(i).Get(0).(string) } +type tCustomLogger struct { + *testing.T + logs []string + errs []string +} + +func (tc *tCustomLogger) Logf(format string, args ...interface{}) { + tc.T.Logf(format, args...) + tc.logs = append(tc.logs, fmt.Sprintf(format, args...)) +} + +func (tc *tCustomLogger) Errorf(format string, args ...interface{}) { + tc.errs = append(tc.errs, fmt.Sprintf(format, args...)) +} + +func (tc *tCustomLogger) FailNow() {} + +func TestLoggingAssertExpectations(t *testing.T) { + m := new(timer) + m.On("GetTime", 0).Return("") + tcl := &tCustomLogger{t, []string{}, []string{}} + + AssertExpectationsForObjects(tcl, m, new(TestExampleImplementation)) + + require.Equal(t, 1, len(tcl.errs)) + 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]) + require.Equal(t, 2, len(tcl.logs)) + assert.Regexp(t, regexp.MustCompile("(?s)FAIL:\tGetTime\\(int\\).*"), tcl.logs[0]) + require.Equal(t, "Expectations didn't match for Mock: *mock.timer", tcl.logs[1]) +} + func TestAfterTotalWaitTimeWhileExecution(t *testing.T) { waitDuration := 1 total, waitMs := 5, time.Millisecond*time.Duration(waitDuration)