diff --git a/mock/mock.go b/mock/mock.go index 8f090fdd9..41257fbeb 100644 --- a/mock/mock.go +++ b/mock/mock.go @@ -273,6 +273,20 @@ func (c *Call) NotBefore(calls ...*Call) *Call { return c } +// InOrder defines the order in which the calls should be made +// +// For example: +// +// InOrder( +// Mock.On("init").Return(nil), +// Mock.On("Do").Return(nil), +// ) +func InOrder(calls ...*Call) { + for i := 1; i < len(calls); i++ { + calls[i].NotBefore(calls[i-1]) + } +} + // Mock is the workhorse used to track activity on another object. // For an example of its usage, refer to the "Example Usage" section at the top // of this document. diff --git a/mock/mock_test.go b/mock/mock_test.go index 95159d852..d28686700 100644 --- a/mock/mock_test.go +++ b/mock/mock_test.go @@ -937,6 +937,26 @@ func Test_Mock_Return_NotBefore_In_Order(t *testing.T) { }) } +func Test_Mock_Return_InOrder_Uses_NotBefore(t *testing.T) { + var mockedService = new(TestExampleImplementation) + + InOrder( + mockedService. + On("TheExampleMethod", 1, 2, 3). + Return(4, nil), + mockedService. + On("TheExampleMethod2", true). + Return(), + ) + + require.NotPanics(t, func() { + mockedService.TheExampleMethod(1, 2, 3) + }) + require.NotPanics(t, func() { + mockedService.TheExampleMethod2(true) + }) +} + func Test_Mock_Return_NotBefore_Out_Of_Order(t *testing.T) { var mockedService = new(TestExampleImplementation) @@ -967,6 +987,35 @@ TheExampleMethod(int,int,int) }) } +func Test_Mock_Return_InOrder_Uses_NotBefore_Out_Of_Order(t *testing.T) { + var mockedService = new(TestExampleImplementation) + + InOrder( + mockedService. + On("TheExampleMethod", 1, 2, 3). + Return(4, nil).Twice(), + mockedService. + On("TheExampleMethod2", true). + Return(), + ) + + expectedPanicString := `mock: Unexpected Method Call +----------------------------- + +TheExampleMethod2(bool) + 0: true + +Must not be called before: + +TheExampleMethod(int,int,int) + 0: 1 + 1: 2 + 2: 3` + require.PanicsWithValue(t, expectedPanicString, func() { + mockedService.TheExampleMethod2(true) + }) +} + func Test_Mock_Return_NotBefore_Not_Enough_Times(t *testing.T) { var mockedService = new(TestExampleImplementation) @@ -1022,6 +1071,7 @@ func Test_Mock_Return_NotBefore_Different_Mock_In_Order(t *testing.T) { mockedService2.TheExampleMethod2(true) }) } + func Test_Mock_Return_NotBefore_Different_Mock_Out_Of_Order(t *testing.T) { var ( mockedService1 = new(TestExampleImplementation)