Allow a method call to be optional

pull/500/head^2
Peter Hsu 2017-09-21 11:02:23 -07:00 committed by Ernesto Jiménez
parent aa8279e896
commit 8ccf48a064
2 changed files with 38 additions and 1 deletions

View File

@ -48,6 +48,9 @@ type Call struct {
// Amount of times this call has been called
totalCalls int
// Call to this method can be optional
optional bool
// Holds a channel that will be used to block the Return until it either
// receives a message or is closed. nil means it returns immediately.
WaitFor <-chan time.Time
@ -148,6 +151,15 @@ func (c *Call) Run(fn func(args Arguments)) *Call {
return c
}
// Maybe allows the method call to be optional. Not calling an optional method
// will not cause an error while asserting expectations
func (c *Call) Maybe() *Call {
c.lock()
defer c.unlock()
c.optional = true
return c
}
// On chains a new expectation description onto the mocked interface. This
// allows syntax like.
//
@ -388,7 +400,7 @@ func (m *Mock) AssertExpectations(t TestingT) bool {
// iterate through each expectation
expectedCalls := m.expectedCalls()
for _, expectedCall := range expectedCalls {
if !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 {
if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 {
somethingMissing = true
failedExpectations++
t.Logf("\u274C\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String())

View File

@ -999,6 +999,31 @@ func Test_Mock_AssertNotCalled(t *testing.T) {
}
func Test_Mock_AssertOptional(t *testing.T) {
// Optional called
var ms1 = new(TestExampleImplementation)
ms1.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil)
ms1.TheExampleMethod(1, 2, 3)
tt1 := new(testing.T)
assert.Equal(t, true, ms1.AssertExpectations(tt1))
// Optional not called
var ms2 = new(TestExampleImplementation)
ms2.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil)
tt2 := new(testing.T)
assert.Equal(t, true, ms2.AssertExpectations(tt2))
// Non-optional called
var ms3 = new(TestExampleImplementation)
ms3.On("TheExampleMethod", 1, 2, 3).Return(4, nil)
ms3.TheExampleMethod(1, 2, 3)
tt3 := new(testing.T)
assert.Equal(t, true, ms3.AssertExpectations(tt3))
}
/*
Arguments helper methods
*/