Skip to content

Commit

Permalink
Adding logging when mock assertions fails
Browse files Browse the repository at this point in the history
  • Loading branch information
Dinesh Kumar authored and ernesto-jimenez committed Feb 6, 2018
1 parent a726187 commit be8372a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions mock/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
32 changes: 32 additions & 0 deletions mock/mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mock
import (
"errors"
"fmt"
"regexp"
"sync"
"testing"
"time"
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit be8372a

Please sign in to comment.