Skip to content

Commit

Permalink
Allow a method call to be optional
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Hsu authored and ernesto-jimenez committed Dec 30, 2017
1 parent aa8279e commit 8ccf48a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
14 changes: 13 additions & 1 deletion mock/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
//
Expand Down Expand Up @@ -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())
Expand Down
25 changes: 25 additions & 0 deletions mock/mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit 8ccf48a

Please sign in to comment.