golang / mock

GoMock is a mocking framework for the Go programming language.
Apache License 2.0
9.3k stars 611 forks source link

Make calls optional #655

Closed MatthiasReumann closed 2 years ago

MatthiasReumann commented 2 years ago

Requested feature call.Optional(), so that a expected function has not to be called.

Why the feature is needed Currently, it is not possible to write universal mocks for all my tests since aborting test due to missing call(s) is thrown. Usually this would not be necessary or even advisable, however, in this particular case it would work just fine and reduces code duplication manifold.

In the following (slimed down) example I create a mock DAO object, which I want to re-use in all different kind of tests. Unfortunately, I can't use it for all tests, since not all Calls are expected.

func GetVideoSectionMock(t *testing.T) dao.VideoSectionDao {
    sectionMock := mock_dao.NewMockVideoSectionDao(gomock.NewController(t))
    sectionMock.EXPECT().Get(id).Return(section, nil)
    sectionMock.EXPECT().Create(section).Return(nil)
    return sectionMock
}
...
func TestSections(t *testing.T) {
      mock := GetVideoSectionMock(t)
      res := onlyCallGet(mock) // onlyCallGet calls sectionMock.Get(...) but not sectionMock.Create(...)
      assert.Equals(section, res)
}

What I've tried is setting minTimes to zero, but that unfortunately also doesn't work.

If there is already a way to circumvent this problem let me know, thanks ❤️ .

MatthiasReumann commented 2 years ago

Solution: .AnyTimes()

From the documentation:

AnyTimes allows the expectation to be called 0 or more times