1 package mock
2
3 import (
4 "errors"
5 "fmt"
6 "regexp"
7 "runtime"
8 "sync"
9 "testing"
10 "time"
11
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 )
15
16
19
20
21 type ExampleInterface interface {
22 TheExampleMethod(a, b, c int) (int, error)
23 }
24
25
26 type TestExampleImplementation struct {
27 Mock
28 }
29
30 func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) {
31 args := i.Called(a, b, c)
32 return args.Int(0), errors.New("Whoops")
33 }
34
35 type options struct {
36 num int
37 str string
38 }
39
40 type OptionFn func(*options)
41
42 func OpNum(n int) OptionFn {
43 return func(o *options) {
44 o.num = n
45 }
46 }
47
48 func OpStr(s string) OptionFn {
49 return func(o *options) {
50 o.str = s
51 }
52 }
53 func (i *TestExampleImplementation) TheExampleMethodFunctionalOptions(x string, opts ...OptionFn) error {
54 args := i.Called(x, opts)
55 return args.Error(0)
56 }
57
58
59 func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) {
60 i.Called(yesorno)
61 }
62
63 type ExampleType struct {
64 ran bool
65 }
66
67 func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error {
68 args := i.Called(et)
69 return args.Error(0)
70 }
71
72 func (i *TestExampleImplementation) TheExampleMethod4(v ExampleInterface) error {
73 args := i.Called(v)
74 return args.Error(0)
75 }
76
77 func (i *TestExampleImplementation) TheExampleMethod5(ch chan struct{}) error {
78 args := i.Called(ch)
79 return args.Error(0)
80 }
81
82 func (i *TestExampleImplementation) TheExampleMethod6(m map[string]bool) error {
83 args := i.Called(m)
84 return args.Error(0)
85 }
86
87 func (i *TestExampleImplementation) TheExampleMethod7(slice []bool) error {
88 args := i.Called(slice)
89 return args.Error(0)
90 }
91
92 func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error {
93 args := i.Called(fn)
94 return args.Error(0)
95 }
96
97 func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error {
98 args := i.Called(a)
99 return args.Error(0)
100 }
101
102 func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error {
103 args := i.Called(a)
104 return args.Error(0)
105 }
106
107 func (i *TestExampleImplementation) TheExampleMethodMixedVariadic(a int, b ...int) error {
108 args := i.Called(a, b)
109 return args.Error(0)
110 }
111
112 type ExampleFuncType func(string) error
113
114 func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error {
115 args := i.Called(fn)
116 return args.Error(0)
117 }
118
119
120 type MockTestingT struct {
121 logfCount, errorfCount, failNowCount int
122 }
123
124 const mockTestingTFailNowCalled = "FailNow was called"
125
126 func (m *MockTestingT) Logf(string, ...interface{}) {
127 m.logfCount++
128 }
129
130 func (m *MockTestingT) Errorf(string, ...interface{}) {
131 m.errorfCount++
132 }
133
134
135
136
137
138
139
140 func (m *MockTestingT) FailNow() {
141 m.failNowCount++
142
143
144 panic(mockTestingTFailNowCalled)
145 }
146
147
150
151 func Test_Mock_TestData(t *testing.T) {
152
153 var mockedService = new(TestExampleImplementation)
154
155 if assert.NotNil(t, mockedService.TestData()) {
156
157 mockedService.TestData().Set("something", 123)
158 assert.Equal(t, 123, mockedService.TestData().Get("something").Data())
159 }
160 }
161
162 func Test_Mock_On(t *testing.T) {
163
164
165 var mockedService = new(TestExampleImplementation)
166
167 c := mockedService.On("TheExampleMethod")
168 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
169 assert.Equal(t, "TheExampleMethod", c.Method)
170 }
171
172 func Test_Mock_Chained_On(t *testing.T) {
173
174 var mockedService = new(TestExampleImplementation)
175
176
177 _, filename, line, _ := runtime.Caller(0)
178 mockedService.
179 On("TheExampleMethod", 1, 2, 3).
180 Return(0).
181 On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
182 Return(nil)
183
184 expectedCalls := []*Call{
185 {
186 Parent: &mockedService.Mock,
187 Method: "TheExampleMethod",
188 Arguments: []interface{}{1, 2, 3},
189 ReturnArguments: []interface{}{0},
190 callerInfo: []string{fmt.Sprintf("%s:%d", filename, line+2)},
191 },
192 {
193 Parent: &mockedService.Mock,
194 Method: "TheExampleMethod3",
195 Arguments: []interface{}{AnythingOfType("*mock.ExampleType")},
196 ReturnArguments: []interface{}{nil},
197 callerInfo: []string{fmt.Sprintf("%s:%d", filename, line+4)},
198 },
199 }
200 assert.Equal(t, expectedCalls, mockedService.ExpectedCalls)
201 }
202
203 func Test_Mock_On_WithArgs(t *testing.T) {
204
205
206 var mockedService = new(TestExampleImplementation)
207
208 c := mockedService.On("TheExampleMethod", 1, 2, 3, 4)
209
210 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
211 assert.Equal(t, "TheExampleMethod", c.Method)
212 assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments)
213 }
214
215 func Test_Mock_On_WithFuncArg(t *testing.T) {
216
217
218 var mockedService = new(TestExampleImplementation)
219
220 c := mockedService.
221 On("TheExampleMethodFunc", AnythingOfType("func(string) error")).
222 Return(nil)
223
224 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
225 assert.Equal(t, "TheExampleMethodFunc", c.Method)
226 assert.Equal(t, 1, len(c.Arguments))
227 assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0])
228
229 fn := func(string) error { return nil }
230
231 assert.NotPanics(t, func() {
232 mockedService.TheExampleMethodFunc(fn)
233 })
234 }
235
236 func Test_Mock_On_WithIntArgMatcher(t *testing.T) {
237 var mockedService TestExampleImplementation
238
239 mockedService.On("TheExampleMethod",
240 MatchedBy(func(a int) bool {
241 return a == 1
242 }), MatchedBy(func(b int) bool {
243 return b == 2
244 }), MatchedBy(func(c int) bool {
245 return c == 3
246 })).Return(0, nil)
247
248 assert.Panics(t, func() {
249 mockedService.TheExampleMethod(1, 2, 4)
250 })
251 assert.Panics(t, func() {
252 mockedService.TheExampleMethod(2, 2, 3)
253 })
254 assert.NotPanics(t, func() {
255 mockedService.TheExampleMethod(1, 2, 3)
256 })
257 }
258
259 func Test_Mock_On_WithArgMatcherThatPanics(t *testing.T) {
260 var mockedService TestExampleImplementation
261
262 mockedService.On("TheExampleMethod2", MatchedBy(func(_ interface{}) bool {
263 panic("try to lock mockedService")
264 })).Return()
265
266 defer func() {
267 assertedExpectations := make(chan struct{})
268 go func() {
269 tt := new(testing.T)
270 mockedService.AssertExpectations(tt)
271 close(assertedExpectations)
272 }()
273 select {
274 case <-assertedExpectations:
275 case <-time.After(time.Second):
276 t.Fatal("AssertExpectations() deadlocked, did the panic leave mockedService locked?")
277 }
278 }()
279
280 assert.Panics(t, func() {
281 mockedService.TheExampleMethod2(false)
282 })
283 }
284
285 func TestMock_WithTest(t *testing.T) {
286 var (
287 mockedService TestExampleImplementation
288 mockedTest MockTestingT
289 )
290
291 mockedService.Test(&mockedTest)
292 mockedService.On("TheExampleMethod", 1, 2, 3).Return(0, nil)
293
294
295
296 mockedService.TheExampleMethod(1, 2, 3)
297
298
299 assert.Equal(t, 0, mockedTest.errorfCount)
300 assert.Equal(t, 0, mockedTest.failNowCount)
301
302
303
304 assert.PanicsWithValue(t, mockTestingTFailNowCalled, func() {
305 mockedService.TheExampleMethod(1, 1, 1)
306 })
307
308
309 assert.Equal(t, 1, mockedTest.errorfCount)
310 assert.Equal(t, 1, mockedTest.failNowCount)
311 }
312
313 func Test_Mock_On_WithPtrArgMatcher(t *testing.T) {
314 var mockedService TestExampleImplementation
315
316 mockedService.On("TheExampleMethod3",
317 MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == true }),
318 ).Return(nil)
319
320 mockedService.On("TheExampleMethod3",
321 MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == false }),
322 ).Return(errors.New("error"))
323
324 mockedService.On("TheExampleMethod3",
325 MatchedBy(func(a *ExampleType) bool { return a == nil }),
326 ).Return(errors.New("error2"))
327
328 assert.Equal(t, mockedService.TheExampleMethod3(&ExampleType{true}), nil)
329 assert.EqualError(t, mockedService.TheExampleMethod3(&ExampleType{false}), "error")
330 assert.EqualError(t, mockedService.TheExampleMethod3(nil), "error2")
331 }
332
333 func Test_Mock_On_WithFuncArgMatcher(t *testing.T) {
334 var mockedService TestExampleImplementation
335
336 fixture1, fixture2 := errors.New("fixture1"), errors.New("fixture2")
337
338 mockedService.On("TheExampleMethodFunc",
339 MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture1 }),
340 ).Return(errors.New("fixture1"))
341
342 mockedService.On("TheExampleMethodFunc",
343 MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture2 }),
344 ).Return(errors.New("fixture2"))
345
346 mockedService.On("TheExampleMethodFunc",
347 MatchedBy(func(a func(string) error) bool { return a == nil }),
348 ).Return(errors.New("fixture3"))
349
350 assert.EqualError(t, mockedService.TheExampleMethodFunc(
351 func(string) error { return fixture1 }), "fixture1")
352 assert.EqualError(t, mockedService.TheExampleMethodFunc(
353 func(string) error { return fixture2 }), "fixture2")
354 assert.EqualError(t, mockedService.TheExampleMethodFunc(nil), "fixture3")
355 }
356
357 func Test_Mock_On_WithInterfaceArgMatcher(t *testing.T) {
358 var mockedService TestExampleImplementation
359
360 mockedService.On("TheExampleMethod4",
361 MatchedBy(func(a ExampleInterface) bool { return a == nil }),
362 ).Return(errors.New("fixture1"))
363
364 assert.EqualError(t, mockedService.TheExampleMethod4(nil), "fixture1")
365 }
366
367 func Test_Mock_On_WithChannelArgMatcher(t *testing.T) {
368 var mockedService TestExampleImplementation
369
370 mockedService.On("TheExampleMethod5",
371 MatchedBy(func(ch chan struct{}) bool { return ch == nil }),
372 ).Return(errors.New("fixture1"))
373
374 assert.EqualError(t, mockedService.TheExampleMethod5(nil), "fixture1")
375 }
376
377 func Test_Mock_On_WithMapArgMatcher(t *testing.T) {
378 var mockedService TestExampleImplementation
379
380 mockedService.On("TheExampleMethod6",
381 MatchedBy(func(m map[string]bool) bool { return m == nil }),
382 ).Return(errors.New("fixture1"))
383
384 assert.EqualError(t, mockedService.TheExampleMethod6(nil), "fixture1")
385 }
386
387 func Test_Mock_On_WithSliceArgMatcher(t *testing.T) {
388 var mockedService TestExampleImplementation
389
390 mockedService.On("TheExampleMethod7",
391 MatchedBy(func(slice []bool) bool { return slice == nil }),
392 ).Return(errors.New("fixture1"))
393
394 assert.EqualError(t, mockedService.TheExampleMethod7(nil), "fixture1")
395 }
396
397 func Test_Mock_On_WithVariadicFunc(t *testing.T) {
398
399
400 var mockedService = new(TestExampleImplementation)
401
402 c := mockedService.
403 On("TheExampleMethodVariadic", []int{1, 2, 3}).
404 Return(nil)
405
406 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
407 assert.Equal(t, 1, len(c.Arguments))
408 assert.Equal(t, []int{1, 2, 3}, c.Arguments[0])
409
410 assert.NotPanics(t, func() {
411 mockedService.TheExampleMethodVariadic(1, 2, 3)
412 })
413 assert.Panics(t, func() {
414 mockedService.TheExampleMethodVariadic(1, 2)
415 })
416
417 }
418
419 func Test_Mock_On_WithMixedVariadicFunc(t *testing.T) {
420
421
422 var mockedService = new(TestExampleImplementation)
423
424 c := mockedService.
425 On("TheExampleMethodMixedVariadic", 1, []int{2, 3, 4}).
426 Return(nil)
427
428 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
429 assert.Equal(t, 2, len(c.Arguments))
430 assert.Equal(t, 1, c.Arguments[0])
431 assert.Equal(t, []int{2, 3, 4}, c.Arguments[1])
432
433 assert.NotPanics(t, func() {
434 mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 4)
435 })
436 assert.Panics(t, func() {
437 mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 5)
438 })
439
440 }
441
442 func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) {
443
444
445 var mockedService = new(TestExampleImplementation)
446
447 c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}).
448 Return(nil)
449
450 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
451 assert.Equal(t, 1, len(c.Arguments))
452 assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0])
453
454 assert.NotPanics(t, func() {
455 mockedService.TheExampleMethodVariadicInterface(1, 2, 3)
456 })
457 assert.Panics(t, func() {
458 mockedService.TheExampleMethodVariadicInterface(1, 2)
459 })
460
461 }
462
463 func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) {
464
465
466 var mockedService = new(TestExampleImplementation)
467
468 var expected []interface{}
469 c := mockedService.
470 On("TheExampleMethodVariadicInterface", expected).
471 Return(nil)
472
473 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
474 assert.Equal(t, 1, len(c.Arguments))
475 assert.Equal(t, expected, c.Arguments[0])
476
477 assert.NotPanics(t, func() {
478 mockedService.TheExampleMethodVariadicInterface()
479 })
480 assert.Panics(t, func() {
481 mockedService.TheExampleMethodVariadicInterface(1, 2)
482 })
483
484 }
485
486 func Test_Mock_On_WithFuncPanics(t *testing.T) {
487
488 var mockedService = new(TestExampleImplementation)
489
490 assert.Panics(t, func() {
491 mockedService.On("TheExampleMethodFunc", func(string) error { return nil })
492 })
493 }
494
495 func Test_Mock_On_WithFuncTypeArg(t *testing.T) {
496
497
498 var mockedService = new(TestExampleImplementation)
499
500 c := mockedService.
501 On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")).
502 Return(nil)
503
504 assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
505 assert.Equal(t, 1, len(c.Arguments))
506 assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0])
507
508 fn := func(string) error { return nil }
509 assert.NotPanics(t, func() {
510 mockedService.TheExampleMethodFuncType(fn)
511 })
512 }
513
514 func Test_Mock_Unset(t *testing.T) {
515
516 var mockedService = new(TestExampleImplementation)
517
518 call := mockedService.
519 On("TheExampleMethodFuncType", "argA").
520 Return("blah")
521
522 found, foundCall := mockedService.findExpectedCall("TheExampleMethodFuncType", "argA")
523 require.NotEqual(t, -1, found)
524 require.Equal(t, foundCall, call)
525
526 call.Unset()
527
528 found, foundCall = mockedService.findExpectedCall("TheExampleMethodFuncType", "argA")
529 require.Equal(t, -1, found)
530
531 var expectedCall *Call
532 require.Equal(t, expectedCall, foundCall)
533
534 fn := func(string) error { return nil }
535 assert.Panics(t, func() {
536 mockedService.TheExampleMethodFuncType(fn)
537 })
538 }
539
540
541
542 func Test_Mock_Chained_UnsetOnlyUnsetsLastCall(t *testing.T) {
543
544 var mockedService = new(TestExampleImplementation)
545
546
547 _, filename, line, _ := runtime.Caller(0)
548 mockedService.
549 On("TheExampleMethod1", 1, 1).
550 Return(0).
551 On("TheExampleMethod2", 2, 2).
552 On("TheExampleMethod3", 3, 3, 3).
553 Return(nil).
554 Unset()
555
556 expectedCalls := []*Call{
557 {
558 Parent: &mockedService.Mock,
559 Method: "TheExampleMethod1",
560 Arguments: []interface{}{1, 1},
561 ReturnArguments: []interface{}{0},
562 callerInfo: []string{fmt.Sprintf("%s:%d", filename, line+2)},
563 },
564 {
565 Parent: &mockedService.Mock,
566 Method: "TheExampleMethod2",
567 Arguments: []interface{}{2, 2},
568 ReturnArguments: []interface{}{},
569 callerInfo: []string{fmt.Sprintf("%s:%d", filename, line+4)},
570 },
571 }
572 assert.Equal(t, 2, len(expectedCalls))
573 assert.Equal(t, expectedCalls, mockedService.ExpectedCalls)
574 }
575
576 func Test_Mock_UnsetIfAlreadyUnsetFails(t *testing.T) {
577
578 var mockedService = new(TestExampleImplementation)
579
580 mock1 := mockedService.
581 On("TheExampleMethod1", 1, 1).
582 Return(1)
583
584 assert.Equal(t, 1, len(mockedService.ExpectedCalls))
585 mock1.Unset()
586 assert.Equal(t, 0, len(mockedService.ExpectedCalls))
587
588 assert.Panics(t, func() {
589 mock1.Unset()
590 })
591
592 assert.Equal(t, 0, len(mockedService.ExpectedCalls))
593 }
594
595 func Test_Mock_UnsetByOnMethodSpec(t *testing.T) {
596
597 var mockedService = new(TestExampleImplementation)
598
599 mock1 := mockedService.
600 On("TheExampleMethod", 1, 2, 3).
601 Return(0, nil)
602
603 assert.Equal(t, 1, len(mockedService.ExpectedCalls))
604 mock1.On("TheExampleMethod", 1, 2, 3).
605 Return(0, nil).Unset()
606
607 assert.Equal(t, 0, len(mockedService.ExpectedCalls))
608
609 assert.Panics(t, func() {
610 mock1.Unset()
611 })
612
613 assert.Equal(t, 0, len(mockedService.ExpectedCalls))
614 }
615
616 func Test_Mock_UnsetByOnMethodSpecAmongOthers(t *testing.T) {
617
618 var mockedService = new(TestExampleImplementation)
619
620 _, filename, line, _ := runtime.Caller(0)
621 mock1 := mockedService.
622 On("TheExampleMethod", 1, 2, 3).
623 Return(0, nil).
624 On("TheExampleMethodVariadic", 1, 2, 3, 4, 5).Once().
625 Return(nil)
626 mock1.
627 On("TheExampleMethodFuncType", Anything).
628 Return(nil)
629
630 assert.Equal(t, 3, len(mockedService.ExpectedCalls))
631 mock1.On("TheExampleMethod", 1, 2, 3).
632 Return(0, nil).Unset()
633
634 assert.Equal(t, 2, len(mockedService.ExpectedCalls))
635
636 expectedCalls := []*Call{
637 {
638 Parent: &mockedService.Mock,
639 Method: "TheExampleMethodVariadic",
640 Repeatability: 1,
641 Arguments: []interface{}{1, 2, 3, 4, 5},
642 ReturnArguments: []interface{}{nil},
643 callerInfo: []string{fmt.Sprintf("%s:%d", filename, line+4)},
644 },
645 {
646 Parent: &mockedService.Mock,
647 Method: "TheExampleMethodFuncType",
648 Arguments: []interface{}{Anything},
649 ReturnArguments: []interface{}{nil},
650 callerInfo: []string{fmt.Sprintf("%s:%d", filename, line+7)},
651 },
652 }
653
654 assert.Equal(t, 2, len(mockedService.ExpectedCalls))
655 assert.Equal(t, expectedCalls, mockedService.ExpectedCalls)
656 }
657
658 func Test_Mock_Unset_WithFuncPanics(t *testing.T) {
659
660 var mockedService = new(TestExampleImplementation)
661 mock1 := mockedService.On("TheExampleMethod", 1)
662 mock1.Arguments = append(mock1.Arguments, func(string) error { return nil })
663
664 assert.Panics(t, func() {
665 mock1.Unset()
666 })
667 }
668
669 func Test_Mock_Return(t *testing.T) {
670
671
672 var mockedService = new(TestExampleImplementation)
673
674 c := mockedService.
675 On("TheExampleMethod", "A", "B", true).
676 Return(1, "two", true)
677
678 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
679
680 call := mockedService.ExpectedCalls[0]
681
682 assert.Equal(t, "TheExampleMethod", call.Method)
683 assert.Equal(t, "A", call.Arguments[0])
684 assert.Equal(t, "B", call.Arguments[1])
685 assert.Equal(t, true, call.Arguments[2])
686 assert.Equal(t, 1, call.ReturnArguments[0])
687 assert.Equal(t, "two", call.ReturnArguments[1])
688 assert.Equal(t, true, call.ReturnArguments[2])
689 assert.Equal(t, 0, call.Repeatability)
690 assert.Nil(t, call.WaitFor)
691 }
692
693 func Test_Mock_Panic(t *testing.T) {
694
695
696 var mockedService = new(TestExampleImplementation)
697
698 c := mockedService.
699 On("TheExampleMethod", "A", "B", true).
700 Panic("panic message for example method")
701
702 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
703
704 call := mockedService.ExpectedCalls[0]
705
706 assert.Equal(t, "TheExampleMethod", call.Method)
707 assert.Equal(t, "A", call.Arguments[0])
708 assert.Equal(t, "B", call.Arguments[1])
709 assert.Equal(t, true, call.Arguments[2])
710 assert.Equal(t, 0, call.Repeatability)
711 assert.Equal(t, 0, call.Repeatability)
712 assert.Equal(t, "panic message for example method", *call.PanicMsg)
713 assert.Nil(t, call.WaitFor)
714 }
715
716 func Test_Mock_Return_WaitUntil(t *testing.T) {
717
718
719 var mockedService = new(TestExampleImplementation)
720 ch := time.After(time.Second)
721
722 c := mockedService.Mock.
723 On("TheExampleMethod", "A", "B", true).
724 WaitUntil(ch).
725 Return(1, "two", true)
726
727
728 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
729
730 call := mockedService.ExpectedCalls[0]
731
732 assert.Equal(t, "TheExampleMethod", call.Method)
733 assert.Equal(t, "A", call.Arguments[0])
734 assert.Equal(t, "B", call.Arguments[1])
735 assert.Equal(t, true, call.Arguments[2])
736 assert.Equal(t, 1, call.ReturnArguments[0])
737 assert.Equal(t, "two", call.ReturnArguments[1])
738 assert.Equal(t, true, call.ReturnArguments[2])
739 assert.Equal(t, 0, call.Repeatability)
740 assert.Equal(t, ch, call.WaitFor)
741 }
742
743 func Test_Mock_Return_After(t *testing.T) {
744
745
746 var mockedService = new(TestExampleImplementation)
747
748 c := mockedService.Mock.
749 On("TheExampleMethod", "A", "B", true).
750 Return(1, "two", true).
751 After(time.Second)
752
753 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
754
755 call := mockedService.Mock.ExpectedCalls[0]
756
757 assert.Equal(t, "TheExampleMethod", call.Method)
758 assert.Equal(t, "A", call.Arguments[0])
759 assert.Equal(t, "B", call.Arguments[1])
760 assert.Equal(t, true, call.Arguments[2])
761 assert.Equal(t, 1, call.ReturnArguments[0])
762 assert.Equal(t, "two", call.ReturnArguments[1])
763 assert.Equal(t, true, call.ReturnArguments[2])
764 assert.Equal(t, 0, call.Repeatability)
765 assert.NotEqual(t, nil, call.WaitFor)
766
767 }
768
769 func Test_Mock_Return_Run(t *testing.T) {
770
771
772 var mockedService = new(TestExampleImplementation)
773
774 fn := func(args Arguments) {
775 arg := args.Get(0).(*ExampleType)
776 arg.ran = true
777 }
778
779 c := mockedService.Mock.
780 On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
781 Return(nil).
782 Run(fn)
783
784 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
785
786 call := mockedService.Mock.ExpectedCalls[0]
787
788 assert.Equal(t, "TheExampleMethod3", call.Method)
789 assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0])
790 assert.Equal(t, nil, call.ReturnArguments[0])
791 assert.Equal(t, 0, call.Repeatability)
792 assert.NotEqual(t, nil, call.WaitFor)
793 assert.NotNil(t, call.Run)
794
795 et := ExampleType{}
796 assert.Equal(t, false, et.ran)
797 mockedService.TheExampleMethod3(&et)
798 assert.Equal(t, true, et.ran)
799 }
800
801 func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) {
802
803 var mockedService = new(TestExampleImplementation)
804 f := func(args Arguments) {
805 arg := args.Get(0).(*ExampleType)
806 arg.ran = true
807 }
808
809 c := mockedService.Mock.
810 On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).
811 Run(f).
812 Return(nil)
813
814 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
815
816 call := mockedService.Mock.ExpectedCalls[0]
817
818 assert.Equal(t, "TheExampleMethod3", call.Method)
819 assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0])
820 assert.Equal(t, nil, call.ReturnArguments[0])
821 assert.Equal(t, 0, call.Repeatability)
822 assert.NotEqual(t, nil, call.WaitFor)
823 assert.NotNil(t, call.Run)
824 }
825
826 func Test_Mock_Return_Once(t *testing.T) {
827
828
829 var mockedService = new(TestExampleImplementation)
830
831 c := mockedService.On("TheExampleMethod", "A", "B", true).
832 Return(1, "two", true).
833 Once()
834
835 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
836
837 call := mockedService.ExpectedCalls[0]
838
839 assert.Equal(t, "TheExampleMethod", call.Method)
840 assert.Equal(t, "A", call.Arguments[0])
841 assert.Equal(t, "B", call.Arguments[1])
842 assert.Equal(t, true, call.Arguments[2])
843 assert.Equal(t, 1, call.ReturnArguments[0])
844 assert.Equal(t, "two", call.ReturnArguments[1])
845 assert.Equal(t, true, call.ReturnArguments[2])
846 assert.Equal(t, 1, call.Repeatability)
847 assert.Nil(t, call.WaitFor)
848 }
849
850 func Test_Mock_Return_Twice(t *testing.T) {
851
852
853 var mockedService = new(TestExampleImplementation)
854
855 c := mockedService.
856 On("TheExampleMethod", "A", "B", true).
857 Return(1, "two", true).
858 Twice()
859
860 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
861
862 call := mockedService.ExpectedCalls[0]
863
864 assert.Equal(t, "TheExampleMethod", call.Method)
865 assert.Equal(t, "A", call.Arguments[0])
866 assert.Equal(t, "B", call.Arguments[1])
867 assert.Equal(t, true, call.Arguments[2])
868 assert.Equal(t, 1, call.ReturnArguments[0])
869 assert.Equal(t, "two", call.ReturnArguments[1])
870 assert.Equal(t, true, call.ReturnArguments[2])
871 assert.Equal(t, 2, call.Repeatability)
872 assert.Nil(t, call.WaitFor)
873 }
874
875 func Test_Mock_Return_Times(t *testing.T) {
876
877
878 var mockedService = new(TestExampleImplementation)
879
880 c := mockedService.
881 On("TheExampleMethod", "A", "B", true).
882 Return(1, "two", true).
883 Times(5)
884
885 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
886
887 call := mockedService.ExpectedCalls[0]
888
889 assert.Equal(t, "TheExampleMethod", call.Method)
890 assert.Equal(t, "A", call.Arguments[0])
891 assert.Equal(t, "B", call.Arguments[1])
892 assert.Equal(t, true, call.Arguments[2])
893 assert.Equal(t, 1, call.ReturnArguments[0])
894 assert.Equal(t, "two", call.ReturnArguments[1])
895 assert.Equal(t, true, call.ReturnArguments[2])
896 assert.Equal(t, 5, call.Repeatability)
897 assert.Nil(t, call.WaitFor)
898 }
899
900 func Test_Mock_Return_Nothing(t *testing.T) {
901
902
903 var mockedService = new(TestExampleImplementation)
904
905 c := mockedService.
906 On("TheExampleMethod", "A", "B", true).
907 Return()
908
909 require.Equal(t, []*Call{c}, mockedService.ExpectedCalls)
910
911 call := mockedService.ExpectedCalls[0]
912
913 assert.Equal(t, "TheExampleMethod", call.Method)
914 assert.Equal(t, "A", call.Arguments[0])
915 assert.Equal(t, "B", call.Arguments[1])
916 assert.Equal(t, true, call.Arguments[2])
917 assert.Equal(t, 0, len(call.ReturnArguments))
918 }
919
920 func Test_Mock_Return_NotBefore_In_Order(t *testing.T) {
921 var mockedService = new(TestExampleImplementation)
922
923 b := mockedService.
924 On("TheExampleMethod", 1, 2, 3).
925 Return(4, nil)
926 c := mockedService.
927 On("TheExampleMethod2", true).
928 Return().
929 NotBefore(b)
930
931 require.Equal(t, []*Call{b, c}, mockedService.ExpectedCalls)
932 require.NotPanics(t, func() {
933 mockedService.TheExampleMethod(1, 2, 3)
934 })
935 require.NotPanics(t, func() {
936 mockedService.TheExampleMethod2(true)
937 })
938 }
939
940 func Test_Mock_Return_NotBefore_Out_Of_Order(t *testing.T) {
941 var mockedService = new(TestExampleImplementation)
942
943 b := mockedService.
944 On("TheExampleMethod", 1, 2, 3).
945 Return(4, nil).Twice()
946 c := mockedService.
947 On("TheExampleMethod2", true).
948 Return().
949 NotBefore(b)
950
951 require.Equal(t, []*Call{b, c}, mockedService.ExpectedCalls)
952
953 expectedPanicString := `mock: Unexpected Method Call
954 -----------------------------
955
956 TheExampleMethod2(bool)
957 0: true
958
959 Must not be called before:
960
961 TheExampleMethod(int,int,int)
962 0: 1
963 1: 2
964 2: 3`
965 require.PanicsWithValue(t, expectedPanicString, func() {
966 mockedService.TheExampleMethod2(true)
967 })
968 }
969
970 func Test_Mock_Return_NotBefore_Not_Enough_Times(t *testing.T) {
971 var mockedService = new(TestExampleImplementation)
972
973 b := mockedService.
974 On("TheExampleMethod", 1, 2, 3).
975 Return(4, nil).Twice()
976 c := mockedService.
977 On("TheExampleMethod2", true).
978 Return().
979 NotBefore(b)
980
981 require.Equal(t, []*Call{b, c}, mockedService.ExpectedCalls)
982
983 require.NotPanics(t, func() {
984 mockedService.TheExampleMethod(1, 2, 3)
985 })
986 expectedPanicString := `mock: Unexpected Method Call
987 -----------------------------
988
989 TheExampleMethod2(bool)
990 0: true
991
992 Must not be called before another call of:
993
994 TheExampleMethod(int,int,int)
995 0: 1
996 1: 2
997 2: 3`
998 require.PanicsWithValue(t, expectedPanicString, func() {
999 mockedService.TheExampleMethod2(true)
1000 })
1001 }
1002
1003 func Test_Mock_Return_NotBefore_Different_Mock_In_Order(t *testing.T) {
1004 var (
1005 mockedService1 = new(TestExampleImplementation)
1006 mockedService2 = new(TestExampleImplementation)
1007 )
1008
1009 b := mockedService1.
1010 On("TheExampleMethod", 1, 2, 3).
1011 Return(4, nil)
1012 c := mockedService2.
1013 On("TheExampleMethod2", true).
1014 Return().
1015 NotBefore(b)
1016
1017 require.Equal(t, []*Call{c}, mockedService2.ExpectedCalls)
1018 require.NotPanics(t, func() {
1019 mockedService1.TheExampleMethod(1, 2, 3)
1020 })
1021 require.NotPanics(t, func() {
1022 mockedService2.TheExampleMethod2(true)
1023 })
1024 }
1025 func Test_Mock_Return_NotBefore_Different_Mock_Out_Of_Order(t *testing.T) {
1026 var (
1027 mockedService1 = new(TestExampleImplementation)
1028 mockedService2 = new(TestExampleImplementation)
1029 )
1030
1031 b := mockedService1.
1032 On("TheExampleMethod", 1, 2, 3).
1033 Return(4, nil)
1034 c := mockedService2.
1035 On("TheExampleMethod2", true).
1036 Return().
1037 NotBefore(b)
1038
1039 require.Equal(t, []*Call{c}, mockedService2.ExpectedCalls)
1040
1041 expectedPanicString := `mock: Unexpected Method Call
1042 -----------------------------
1043
1044 TheExampleMethod2(bool)
1045 0: true
1046
1047 Must not be called before method from another mock instance:
1048
1049 TheExampleMethod(int,int,int)
1050 0: 1
1051 1: 2
1052 2: 3`
1053 require.PanicsWithValue(t, expectedPanicString, func() {
1054 mockedService2.TheExampleMethod2(true)
1055 })
1056 }
1057
1058 func Test_Mock_Return_NotBefore_In_Order_With_Non_Dependant(t *testing.T) {
1059 var mockedService = new(TestExampleImplementation)
1060
1061 a := mockedService.
1062 On("TheExampleMethod", 1, 2, 3).
1063 Return(4, nil)
1064 b := mockedService.
1065 On("TheExampleMethod", 4, 5, 6).
1066 Return(4, nil)
1067 c := mockedService.
1068 On("TheExampleMethod2", true).
1069 Return().
1070 NotBefore(a, b)
1071 d := mockedService.
1072 On("TheExampleMethod7", []bool{}).Return(nil)
1073
1074 require.Equal(t, []*Call{a, b, c, d}, mockedService.ExpectedCalls)
1075 require.NotPanics(t, func() {
1076 mockedService.TheExampleMethod7([]bool{})
1077 })
1078 require.NotPanics(t, func() {
1079 mockedService.TheExampleMethod(1, 2, 3)
1080 })
1081 require.NotPanics(t, func() {
1082 mockedService.TheExampleMethod7([]bool{})
1083 })
1084 require.NotPanics(t, func() {
1085 mockedService.TheExampleMethod(4, 5, 6)
1086 })
1087 require.NotPanics(t, func() {
1088 mockedService.TheExampleMethod7([]bool{})
1089 })
1090 require.NotPanics(t, func() {
1091 mockedService.TheExampleMethod2(true)
1092 })
1093 require.NotPanics(t, func() {
1094 mockedService.TheExampleMethod7([]bool{})
1095 })
1096 }
1097
1098 func Test_Mock_Return_NotBefore_Orphan_Call(t *testing.T) {
1099 var mockedService = new(TestExampleImplementation)
1100
1101 require.PanicsWithValue(t, "not before calls must be created with Mock.On()", func() {
1102 mockedService.
1103 On("TheExampleMethod2", true).
1104 Return().
1105 NotBefore(&Call{Method: "Not", Arguments: Arguments{"how", "it's"}, ReturnArguments: Arguments{"done"}})
1106 })
1107 }
1108
1109 func Test_Mock_findExpectedCall(t *testing.T) {
1110
1111 m := new(Mock)
1112 m.On("One", 1).Return("one")
1113 m.On("Two", 2).Return("two")
1114 m.On("Two", 3).Return("three")
1115
1116 f, c := m.findExpectedCall("Two", 3)
1117
1118 if assert.Equal(t, 2, f) {
1119 if assert.NotNil(t, c) {
1120 assert.Equal(t, "Two", c.Method)
1121 assert.Equal(t, 3, c.Arguments[0])
1122 assert.Equal(t, "three", c.ReturnArguments[0])
1123 }
1124 }
1125
1126 }
1127
1128 func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) {
1129
1130 m := new(Mock)
1131 m.On("One", 1).Return("one")
1132 m.On("Two", 2).Return("two")
1133 m.On("Two", 3).Return("three")
1134
1135 f, _ := m.findExpectedCall("Two")
1136
1137 assert.Equal(t, -1, f)
1138
1139 }
1140
1141 func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) {
1142
1143 m := new(Mock)
1144 m.On("One", 1).Return("one")
1145 m.On("Two", 2).Return("two").Once()
1146 m.On("Two", 3).Return("three").Twice()
1147 m.On("Two", 3).Return("three").Times(8)
1148
1149 f, c := m.findExpectedCall("Two", 3)
1150
1151 if assert.Equal(t, 2, f) {
1152 if assert.NotNil(t, c) {
1153 assert.Equal(t, "Two", c.Method)
1154 assert.Equal(t, 3, c.Arguments[0])
1155 assert.Equal(t, "three", c.ReturnArguments[0])
1156 }
1157 }
1158
1159 c = m.On("Once", 1).Return("one").Once()
1160 c.Repeatability = -1
1161 f, c = m.findExpectedCall("Once", 1)
1162 if assert.Equal(t, -1, f) {
1163 if assert.NotNil(t, c) {
1164 assert.Equal(t, "Once", c.Method)
1165 assert.Equal(t, 1, c.Arguments[0])
1166 assert.Equal(t, "one", c.ReturnArguments[0])
1167 }
1168 }
1169 }
1170
1171 func Test_callString(t *testing.T) {
1172
1173 assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false))
1174 assert.Equal(t, `Method(<nil>)`, callString("Method", []interface{}{nil}, false))
1175
1176 }
1177
1178 func Test_Mock_Called(t *testing.T) {
1179
1180 var mockedService = new(TestExampleImplementation)
1181
1182 mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true)
1183
1184 returnArguments := mockedService.Called(1, 2, 3)
1185
1186 if assert.Equal(t, 1, len(mockedService.Calls)) {
1187 assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method)
1188 assert.Equal(t, 1, mockedService.Calls[0].Arguments[0])
1189 assert.Equal(t, 2, mockedService.Calls[0].Arguments[1])
1190 assert.Equal(t, 3, mockedService.Calls[0].Arguments[2])
1191 }
1192
1193 if assert.Equal(t, 3, len(returnArguments)) {
1194 assert.Equal(t, 5, returnArguments[0])
1195 assert.Equal(t, "6", returnArguments[1])
1196 assert.Equal(t, true, returnArguments[2])
1197 }
1198
1199 }
1200
1201 func asyncCall(m *Mock, ch chan Arguments) {
1202 ch <- m.Called(1, 2, 3)
1203 }
1204
1205 func Test_Mock_Called_blocks(t *testing.T) {
1206
1207 var mockedService = new(TestExampleImplementation)
1208
1209 mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond)
1210
1211 ch := make(chan Arguments)
1212
1213 go asyncCall(&mockedService.Mock, ch)
1214
1215 select {
1216 case <-ch:
1217 t.Fatal("should have waited")
1218 case <-time.After(1 * time.Millisecond):
1219 }
1220
1221 returnArguments := <-ch
1222
1223 if assert.Equal(t, 1, len(mockedService.Mock.Calls)) {
1224 assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method)
1225 assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0])
1226 assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1])
1227 assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2])
1228 }
1229
1230 if assert.Equal(t, 3, len(returnArguments)) {
1231 assert.Equal(t, 5, returnArguments[0])
1232 assert.Equal(t, "6", returnArguments[1])
1233 assert.Equal(t, true, returnArguments[2])
1234 }
1235
1236 }
1237
1238 func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) {
1239
1240 var mockedService = new(TestExampleImplementation)
1241
1242 mockedService.
1243 On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).
1244 Return(5, "6", true).
1245 Once()
1246 mockedService.
1247 On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3).
1248 Return(-1, "hi", false)
1249
1250 returnArguments1 := mockedService.Called(1, 2, 3)
1251 returnArguments2 := mockedService.Called(1, 2, 3)
1252
1253 if assert.Equal(t, 2, len(mockedService.Calls)) {
1254 assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method)
1255 assert.Equal(t, 1, mockedService.Calls[0].Arguments[0])
1256 assert.Equal(t, 2, mockedService.Calls[0].Arguments[1])
1257 assert.Equal(t, 3, mockedService.Calls[0].Arguments[2])
1258
1259 assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method)
1260 assert.Equal(t, 1, mockedService.Calls[1].Arguments[0])
1261 assert.Equal(t, 2, mockedService.Calls[1].Arguments[1])
1262 assert.Equal(t, 3, mockedService.Calls[1].Arguments[2])
1263 }
1264
1265 if assert.Equal(t, 3, len(returnArguments1)) {
1266 assert.Equal(t, 5, returnArguments1[0])
1267 assert.Equal(t, "6", returnArguments1[1])
1268 assert.Equal(t, true, returnArguments1[2])
1269 }
1270
1271 if assert.Equal(t, 3, len(returnArguments2)) {
1272 assert.Equal(t, -1, returnArguments2[0])
1273 assert.Equal(t, "hi", returnArguments2[1])
1274 assert.Equal(t, false, returnArguments2[2])
1275 }
1276
1277 }
1278
1279 func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) {
1280
1281 var mockedService = new(TestExampleImplementation)
1282
1283 mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4)
1284
1285 mockedService.TheExampleMethod(1, 2, 3)
1286 mockedService.TheExampleMethod(1, 2, 3)
1287 mockedService.TheExampleMethod(1, 2, 3)
1288 mockedService.TheExampleMethod(1, 2, 3)
1289 assert.Panics(t, func() {
1290 mockedService.TheExampleMethod(1, 2, 3)
1291 })
1292
1293 }
1294
1295 func Test_Mock_Called_Unexpected(t *testing.T) {
1296
1297 var mockedService = new(TestExampleImplementation)
1298
1299
1300 assert.Panics(t, func() {
1301 mockedService.Called(1, 2, 3)
1302 }, "Calling unexpected method should panic")
1303
1304 }
1305
1306 func Test_AssertExpectationsForObjects_Helper(t *testing.T) {
1307
1308 var mockedService1 = new(TestExampleImplementation)
1309 var mockedService2 = new(TestExampleImplementation)
1310 var mockedService3 = new(TestExampleImplementation)
1311 var mockedService4 = new(TestExampleImplementation)
1312
1313 mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return()
1314 mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return()
1315 mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return()
1316
1317 mockedService1.Called(1)
1318 mockedService2.Called(2)
1319 mockedService3.Called(3)
1320
1321 assert.True(t, AssertExpectationsForObjects(t, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock, &mockedService4.Mock))
1322 assert.True(t, AssertExpectationsForObjects(t, mockedService1, mockedService2, mockedService3, mockedService4))
1323
1324 }
1325
1326 func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) {
1327
1328 var mockedService1 = new(TestExampleImplementation)
1329 var mockedService2 = new(TestExampleImplementation)
1330 var mockedService3 = new(TestExampleImplementation)
1331
1332 mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return()
1333 mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return()
1334 mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return()
1335
1336 mockedService1.Called(1)
1337 mockedService3.Called(3)
1338
1339 tt := new(testing.T)
1340 assert.False(t, AssertExpectationsForObjects(tt, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock))
1341 assert.False(t, AssertExpectationsForObjects(tt, mockedService1, mockedService2, mockedService3))
1342
1343 }
1344
1345 func Test_Mock_AssertExpectations(t *testing.T) {
1346
1347 var mockedService = new(TestExampleImplementation)
1348
1349 mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7)
1350
1351 tt := new(testing.T)
1352 assert.False(t, mockedService.AssertExpectations(tt))
1353
1354
1355 mockedService.Called(1, 2, 3)
1356
1357
1358 assert.True(t, mockedService.AssertExpectations(tt))
1359
1360 }
1361
1362 func Test_Mock_AssertExpectations_Placeholder_NoArgs(t *testing.T) {
1363
1364 var mockedService = new(TestExampleImplementation)
1365
1366 mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(5, 6, 7).Once()
1367 mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(7, 6, 5)
1368
1369 tt := new(testing.T)
1370 assert.False(t, mockedService.AssertExpectations(tt))
1371
1372
1373 mockedService.Called()
1374
1375
1376 assert.True(t, mockedService.AssertExpectations(tt))
1377
1378 }
1379
1380 func Test_Mock_AssertExpectations_Placeholder(t *testing.T) {
1381
1382 var mockedService = new(TestExampleImplementation)
1383
1384 mockedService.On("Test_Mock_AssertExpectations_Placeholder", 1, 2, 3).Return(5, 6, 7).Once()
1385 mockedService.On("Test_Mock_AssertExpectations_Placeholder", 3, 2, 1).Return(7, 6, 5)
1386
1387 tt := new(testing.T)
1388 assert.False(t, mockedService.AssertExpectations(tt))
1389
1390
1391 mockedService.Called(1, 2, 3)
1392
1393
1394 assert.False(t, mockedService.AssertExpectations(tt))
1395
1396
1397 mockedService.Called(3, 2, 1)
1398
1399
1400 assert.True(t, mockedService.AssertExpectations(tt))
1401 }
1402
1403 func Test_Mock_AssertExpectations_With_Pointers(t *testing.T) {
1404
1405 var mockedService = new(TestExampleImplementation)
1406
1407 mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{1}).Return(1)
1408 mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{2}).Return(2)
1409
1410 tt := new(testing.T)
1411 assert.False(t, mockedService.AssertExpectations(tt))
1412
1413 s := struct{ Foo int }{1}
1414
1415 mockedService.Called(&s)
1416 s.Foo = 2
1417 mockedService.Called(&s)
1418
1419
1420 assert.True(t, mockedService.AssertExpectations(tt))
1421
1422 }
1423
1424 func Test_Mock_AssertExpectationsCustomType(t *testing.T) {
1425
1426 var mockedService = new(TestExampleImplementation)
1427
1428 mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once()
1429
1430 tt := new(testing.T)
1431 assert.False(t, mockedService.AssertExpectations(tt))
1432
1433
1434 mockedService.TheExampleMethod3(&ExampleType{})
1435
1436
1437 assert.True(t, mockedService.AssertExpectations(tt))
1438
1439 }
1440
1441 func Test_Mock_AssertExpectationsFunctionalOptionsType(t *testing.T) {
1442
1443 var mockedService = new(TestExampleImplementation)
1444
1445 mockedService.On("TheExampleMethodFunctionalOptions", "test", FunctionalOptions(OpNum(1), OpStr("foo"))).Return(nil).Once()
1446
1447 tt := new(testing.T)
1448 assert.False(t, mockedService.AssertExpectations(tt))
1449
1450
1451 mockedService.TheExampleMethodFunctionalOptions("test", OpNum(1), OpStr("foo"))
1452
1453
1454 assert.True(t, mockedService.AssertExpectations(tt))
1455
1456 }
1457
1458 func Test_Mock_AssertExpectationsFunctionalOptionsType_Empty(t *testing.T) {
1459
1460 var mockedService = new(TestExampleImplementation)
1461
1462 mockedService.On("TheExampleMethodFunctionalOptions", "test", FunctionalOptions()).Return(nil).Once()
1463
1464 tt := new(testing.T)
1465 assert.False(t, mockedService.AssertExpectations(tt))
1466
1467
1468 mockedService.TheExampleMethodFunctionalOptions("test")
1469
1470
1471 assert.True(t, mockedService.AssertExpectations(tt))
1472
1473 }
1474
1475 func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) {
1476
1477 var mockedService = new(TestExampleImplementation)
1478
1479 mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice()
1480
1481 tt := new(testing.T)
1482 assert.False(t, mockedService.AssertExpectations(tt))
1483
1484
1485 mockedService.Called(1, 2, 3)
1486
1487 assert.False(t, mockedService.AssertExpectations(tt))
1488
1489 mockedService.Called(1, 2, 3)
1490
1491
1492 assert.True(t, mockedService.AssertExpectations(tt))
1493
1494 }
1495
1496 func Test_Mock_AssertExpectations_Skipped_Test(t *testing.T) {
1497
1498 var mockedService = new(TestExampleImplementation)
1499
1500 mockedService.On("Test_Mock_AssertExpectations_Skipped_Test", 1, 2, 3).Return(5, 6, 7)
1501 defer mockedService.AssertExpectations(t)
1502
1503 t.Skip("skipping test to ensure AssertExpectations does not fail")
1504 }
1505
1506 func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) {
1507
1508 var mockedService = new(TestExampleImplementation)
1509
1510 mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7)
1511 mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7)
1512
1513 args1 := mockedService.Called(1, 2, 3)
1514 assert.Equal(t, 5, args1.Int(0))
1515 assert.Equal(t, 6, args1.Int(1))
1516 assert.Equal(t, 7, args1.Int(2))
1517
1518 args2 := mockedService.Called(4, 5, 6)
1519 assert.Equal(t, 5, args2.Int(0))
1520 assert.Equal(t, 6, args2.Int(1))
1521 assert.Equal(t, 7, args2.Int(2))
1522
1523 }
1524
1525 func Test_Mock_AssertNumberOfCalls(t *testing.T) {
1526
1527 var mockedService = new(TestExampleImplementation)
1528
1529 mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7)
1530
1531 mockedService.Called(1, 2, 3)
1532 assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1))
1533
1534 mockedService.Called(1, 2, 3)
1535 assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2))
1536
1537 }
1538
1539 func Test_Mock_AssertCalled(t *testing.T) {
1540
1541 var mockedService = new(TestExampleImplementation)
1542
1543 mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7)
1544
1545 mockedService.Called(1, 2, 3)
1546
1547 assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3))
1548
1549 }
1550
1551 func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) {
1552
1553 var mockedService = new(TestExampleImplementation)
1554
1555 mockedService.
1556 On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything).
1557 Return()
1558
1559 mockedService.Called(1, "two", []uint8("three"))
1560
1561 assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8")))
1562
1563 }
1564
1565 func Test_Mock_AssertCalled_WithArguments(t *testing.T) {
1566
1567 var mockedService = new(TestExampleImplementation)
1568
1569 mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7)
1570
1571 mockedService.Called(1, 2, 3)
1572
1573 tt := new(testing.T)
1574 assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3))
1575 assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4))
1576
1577 }
1578
1579 func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) {
1580
1581 var mockedService = new(TestExampleImplementation)
1582
1583 mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once()
1584 mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once()
1585
1586 mockedService.Called(1, 2, 3)
1587 mockedService.Called(2, 3, 4)
1588
1589 tt := new(testing.T)
1590 assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3))
1591 assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4))
1592 assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5))
1593
1594 }
1595
1596 func Test_Mock_AssertNotCalled(t *testing.T) {
1597
1598 var mockedService = new(TestExampleImplementation)
1599
1600 mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7)
1601
1602 mockedService.Called(1, 2, 3)
1603
1604 assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled"))
1605
1606 }
1607
1608 func Test_Mock_IsMethodCallable(t *testing.T) {
1609 var mockedService = new(TestExampleImplementation)
1610
1611 arg := []Call{{Repeatability: 1}, {Repeatability: 2}}
1612 arg2 := []Call{{Repeatability: 1}, {Repeatability: 1}}
1613 arg3 := []Call{{Repeatability: 1}, {Repeatability: 1}}
1614
1615 mockedService.On("Test_Mock_IsMethodCallable", arg2).Return(true).Twice()
1616
1617 assert.False(t, mockedService.IsMethodCallable(t, "Test_Mock_IsMethodCallable", arg))
1618 assert.True(t, mockedService.IsMethodCallable(t, "Test_Mock_IsMethodCallable", arg2))
1619 assert.True(t, mockedService.IsMethodCallable(t, "Test_Mock_IsMethodCallable", arg3))
1620
1621 mockedService.MethodCalled("Test_Mock_IsMethodCallable", arg2)
1622 mockedService.MethodCalled("Test_Mock_IsMethodCallable", arg2)
1623
1624 assert.False(t, mockedService.IsMethodCallable(t, "Test_Mock_IsMethodCallable", arg2))
1625 }
1626
1627 func TestIsArgsEqual(t *testing.T) {
1628 var expected = Arguments{5, 3, 4, 6, 7, 2}
1629
1630
1631 args := append(([]interface{})(nil), expected[1:]...)
1632 args[2] = expected[1]
1633 assert.False(t, isArgsEqual(expected, args))
1634
1635
1636 arr := append(([]interface{})(nil), expected...)
1637 assert.True(t, isArgsEqual(expected, arr))
1638 }
1639
1640 func Test_Mock_AssertOptional(t *testing.T) {
1641
1642 var ms1 = new(TestExampleImplementation)
1643 ms1.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil)
1644 ms1.TheExampleMethod(1, 2, 3)
1645
1646 tt1 := new(testing.T)
1647 assert.Equal(t, true, ms1.AssertExpectations(tt1))
1648
1649
1650 var ms2 = new(TestExampleImplementation)
1651 ms2.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil)
1652
1653 tt2 := new(testing.T)
1654 assert.Equal(t, true, ms2.AssertExpectations(tt2))
1655
1656
1657 var ms3 = new(TestExampleImplementation)
1658 ms3.On("TheExampleMethod", 1, 2, 3).Return(4, nil)
1659 ms3.TheExampleMethod(1, 2, 3)
1660
1661 tt3 := new(testing.T)
1662 assert.Equal(t, true, ms3.AssertExpectations(tt3))
1663 }
1664
1665
1668 func Test_Arguments_Get(t *testing.T) {
1669
1670 var args = Arguments([]interface{}{"string", 123, true})
1671
1672 assert.Equal(t, "string", args.Get(0).(string))
1673 assert.Equal(t, 123, args.Get(1).(int))
1674 assert.Equal(t, true, args.Get(2).(bool))
1675
1676 }
1677
1678 func Test_Arguments_Is(t *testing.T) {
1679
1680 var args = Arguments([]interface{}{"string", 123, true})
1681
1682 assert.True(t, args.Is("string", 123, true))
1683 assert.False(t, args.Is("wrong", 456, false))
1684
1685 }
1686
1687 func Test_Arguments_Diff(t *testing.T) {
1688
1689 var args = Arguments([]interface{}{"Hello World", 123, true})
1690 var diff string
1691 var count int
1692 diff, count = args.Diff([]interface{}{"Hello World", 456, "false"})
1693
1694 assert.Equal(t, 2, count)
1695 assert.Contains(t, diff, `(int=456) != (int=123)`)
1696 assert.Contains(t, diff, `(string=false) != (bool=true)`)
1697
1698 }
1699
1700 func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) {
1701
1702 var args = Arguments([]interface{}{"string", 123, true})
1703 var diff string
1704 var count int
1705 diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"})
1706
1707 assert.Equal(t, 3, count)
1708 assert.Contains(t, diff, `(string=extra) != (Missing)`)
1709
1710 }
1711
1712 func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) {
1713
1714 var args = Arguments([]interface{}{"string", 123, true})
1715 var count int
1716 _, count = args.Diff([]interface{}{"string", Anything, true})
1717
1718 assert.Equal(t, 0, count)
1719
1720 }
1721
1722 func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) {
1723
1724 var args = Arguments([]interface{}{"string", Anything, true})
1725 var count int
1726 _, count = args.Diff([]interface{}{"string", 123, true})
1727
1728 assert.Equal(t, 0, count)
1729
1730 }
1731
1732 func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) {
1733
1734 var args = Arguments([]interface{}{"string", AnythingOfType("int"), true})
1735 var count int
1736 _, count = args.Diff([]interface{}{"string", 123, true})
1737
1738 assert.Equal(t, 0, count)
1739
1740 }
1741
1742 func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) {
1743
1744 var args = Arguments([]interface{}{"string", AnythingOfType("string"), true})
1745 var count int
1746 var diff string
1747 diff, count = args.Diff([]interface{}{"string", 123, true})
1748
1749 assert.Equal(t, 1, count)
1750 assert.Contains(t, diff, `string != type int - (int=123)`)
1751
1752 }
1753
1754 func Test_Arguments_Diff_WithIsTypeArgument(t *testing.T) {
1755 var args = Arguments([]interface{}{"string", IsType(0), true})
1756 var count int
1757 _, count = args.Diff([]interface{}{"string", 123, true})
1758
1759 assert.Equal(t, 0, count)
1760 }
1761
1762 func Test_Arguments_Diff_WithIsTypeArgument_Failing(t *testing.T) {
1763 var args = Arguments([]interface{}{"string", IsType(""), true})
1764 var count int
1765 var diff string
1766 diff, count = args.Diff([]interface{}{"string", 123, true})
1767
1768 assert.Equal(t, 1, count)
1769 assert.Contains(t, diff, `string != type int - (int=123)`)
1770 }
1771
1772 func Test_Arguments_Diff_WithArgMatcher(t *testing.T) {
1773 matchFn := func(a int) bool {
1774 return a == 123
1775 }
1776 var args = Arguments([]interface{}{"string", MatchedBy(matchFn), true})
1777
1778 diff, count := args.Diff([]interface{}{"string", 124, true})
1779 assert.Equal(t, 1, count)
1780 assert.Contains(t, diff, `(int=124) not matched by func(int) bool`)
1781
1782 diff, count = args.Diff([]interface{}{"string", false, true})
1783 assert.Equal(t, 1, count)
1784 assert.Contains(t, diff, `(bool=false) not matched by func(int) bool`)
1785
1786 diff, count = args.Diff([]interface{}{"string", 123, false})
1787 assert.Equal(t, 1, count)
1788 assert.Contains(t, diff, `(int=123) matched by func(int) bool`)
1789
1790 diff, count = args.Diff([]interface{}{"string", 123, true})
1791 assert.Equal(t, 0, count)
1792 assert.Contains(t, diff, `No differences.`)
1793 }
1794
1795 func Test_Arguments_Assert(t *testing.T) {
1796
1797 var args = Arguments([]interface{}{"string", 123, true})
1798
1799 assert.True(t, args.Assert(t, "string", 123, true))
1800
1801 }
1802
1803 func Test_Arguments_String_Representation(t *testing.T) {
1804
1805 var args = Arguments([]interface{}{"string", 123, true})
1806 assert.Equal(t, `string,int,bool`, args.String())
1807
1808 }
1809
1810 func Test_Arguments_String(t *testing.T) {
1811
1812 var args = Arguments([]interface{}{"string", 123, true})
1813 assert.Equal(t, "string", args.String(0))
1814
1815 }
1816
1817 func Test_Arguments_Error(t *testing.T) {
1818
1819 var err = errors.New("An Error")
1820 var args = Arguments([]interface{}{"string", 123, true, err})
1821 assert.Equal(t, err, args.Error(3))
1822
1823 }
1824
1825 func Test_Arguments_Error_Nil(t *testing.T) {
1826
1827 var args = Arguments([]interface{}{"string", 123, true, nil})
1828 assert.Equal(t, nil, args.Error(3))
1829
1830 }
1831
1832 func Test_Arguments_Int(t *testing.T) {
1833
1834 var args = Arguments([]interface{}{"string", 123, true})
1835 assert.Equal(t, 123, args.Int(1))
1836
1837 }
1838
1839 func Test_Arguments_Bool(t *testing.T) {
1840
1841 var args = Arguments([]interface{}{"string", 123, true})
1842 assert.Equal(t, true, args.Bool(2))
1843
1844 }
1845
1846 func Test_WaitUntil_Parallel(t *testing.T) {
1847
1848
1849 var mockedService = new(TestExampleImplementation)
1850
1851 ch1 := make(chan time.Time)
1852 ch2 := make(chan time.Time)
1853
1854 mockedService.Mock.On("TheExampleMethod2", true).Return().WaitUntil(ch2).Run(func(args Arguments) {
1855 ch1 <- time.Now()
1856 })
1857
1858 mockedService.Mock.On("TheExampleMethod2", false).Return().WaitUntil(ch1)
1859
1860
1861 go func() {
1862 mockedService.TheExampleMethod2(false)
1863 }()
1864 go func() {
1865 mockedService.TheExampleMethod2(true)
1866 }()
1867
1868
1869 ch2 <- time.Now()
1870 }
1871
1872 func Test_MockMethodCalled(t *testing.T) {
1873 m := new(Mock)
1874 m.On("foo", "hello").Return("world")
1875
1876 retArgs := m.MethodCalled("foo", "hello")
1877 require.True(t, len(retArgs) == 1)
1878 require.Equal(t, "world", retArgs[0])
1879 m.AssertExpectations(t)
1880 }
1881
1882 func Test_MockMethodCalled_Panic(t *testing.T) {
1883 m := new(Mock)
1884 m.On("foo", "hello").Panic("world panics")
1885
1886 require.PanicsWithValue(t, "world panics", func() { m.MethodCalled("foo", "hello") })
1887 m.AssertExpectations(t)
1888 }
1889
1890
1891 func Test_MockReturnAndCalledConcurrent(t *testing.T) {
1892 iterations := 1000
1893 m := &Mock{}
1894 call := m.On("ConcurrencyTestMethod")
1895
1896 wg := sync.WaitGroup{}
1897 wg.Add(2)
1898
1899 go func() {
1900 for i := 0; i < iterations; i++ {
1901 call.Return(10)
1902 }
1903 wg.Done()
1904 }()
1905 go func() {
1906 for i := 0; i < iterations; i++ {
1907 ConcurrencyTestMethod(m)
1908 }
1909 wg.Done()
1910 }()
1911 wg.Wait()
1912 }
1913
1914 type timer struct{ Mock }
1915
1916 func (s *timer) GetTime(i int) string {
1917 return s.Called(i).Get(0).(string)
1918 }
1919
1920 func (s *timer) GetTimes(times []int) string {
1921 return s.Called(times).Get(0).(string)
1922 }
1923
1924 type tCustomLogger struct {
1925 *testing.T
1926 logs []string
1927 errs []string
1928 }
1929
1930 func (tc *tCustomLogger) Logf(format string, args ...interface{}) {
1931 tc.T.Logf(format, args...)
1932 tc.logs = append(tc.logs, fmt.Sprintf(format, args...))
1933 }
1934
1935 func (tc *tCustomLogger) Errorf(format string, args ...interface{}) {
1936 tc.errs = append(tc.errs, fmt.Sprintf(format, args...))
1937 }
1938
1939 func (tc *tCustomLogger) FailNow() {}
1940
1941 func TestLoggingAssertExpectations(t *testing.T) {
1942 m := new(timer)
1943 m.On("GetTime", 0).Return("")
1944 tcl := &tCustomLogger{t, []string{}, []string{}}
1945
1946 AssertExpectationsForObjects(tcl, m, new(TestExampleImplementation))
1947
1948 require.Equal(t, 1, len(tcl.errs))
1949 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])
1950 require.Equal(t, 2, len(tcl.logs))
1951 assert.Regexp(t, regexp.MustCompile("(?s)FAIL:\tGetTime\\(int\\).*"), tcl.logs[0])
1952 require.Equal(t, "Expectations didn't match for Mock: *mock.timer", tcl.logs[1])
1953 }
1954
1955 func TestAfterTotalWaitTimeWhileExecution(t *testing.T) {
1956 waitDuration := 1
1957 total, waitMs := 5, time.Millisecond*time.Duration(waitDuration)
1958 aTimer := new(timer)
1959 for i := 0; i < total; i++ {
1960 aTimer.On("GetTime", i).After(waitMs).Return(fmt.Sprintf("Time%d", i)).Once()
1961 }
1962 time.Sleep(waitMs)
1963 start := time.Now()
1964 var results []string
1965
1966 for i := 0; i < total; i++ {
1967 results = append(results, aTimer.GetTime(i))
1968 }
1969
1970 end := time.Now()
1971 elapsedTime := end.Sub(start)
1972 assert.True(t, elapsedTime > waitMs, fmt.Sprintf("Total elapsed time:%v should be at least greater than %v", elapsedTime, waitMs))
1973 assert.Equal(t, total, len(results))
1974 for i := range results {
1975 assert.Equal(t, fmt.Sprintf("Time%d", i), results[i], "Return value of method should be same")
1976 }
1977 }
1978
1979 func TestArgumentMatcherToPrintMismatch(t *testing.T) {
1980 defer func() {
1981 if r := recover(); r != nil {
1982 matchingExp := regexp.MustCompile(
1983 `\s+mock: Unexpected Method Call\s+-*\s+GetTime\(int\)\s+0: 1\s+The closest call I have is:\s+GetTime\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(int=1\) not matched by func\(int\) bool`)
1984 assert.Regexp(t, matchingExp, r)
1985 }
1986 }()
1987
1988 m := new(timer)
1989 m.On("GetTime", MatchedBy(func(i int) bool { return false })).Return("SomeTime").Once()
1990
1991 res := m.GetTime(1)
1992 require.Equal(t, "SomeTime", res)
1993 m.AssertExpectations(t)
1994 }
1995
1996 func TestArgumentMatcherToPrintMismatchWithReferenceType(t *testing.T) {
1997 defer func() {
1998 if r := recover(); r != nil {
1999 matchingExp := regexp.MustCompile(
2000 `\s+mock: Unexpected Method Call\s+-*\s+GetTimes\(\[\]int\)\s+0: \[\]int\{1\}\s+The closest call I have is:\s+GetTimes\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(\[\]int=\[1\]\) not matched by func\(\[\]int\) bool`)
2001 assert.Regexp(t, matchingExp, r)
2002 }
2003 }()
2004
2005 m := new(timer)
2006 m.On("GetTimes", MatchedBy(func(_ []int) bool { return false })).Return("SomeTime").Once()
2007
2008 res := m.GetTimes([]int{1})
2009 require.Equal(t, "SomeTime", res)
2010 m.AssertExpectations(t)
2011 }
2012
2013 func TestClosestCallMismatchedArgumentInformationShowsTheClosest(t *testing.T) {
2014 defer func() {
2015 if r := recover(); r != nil {
2016 matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod(int,int,int)`, `0: 1\s+1: 1\s+2: 2`, `0: 1\s+1: 1\s+2: 1`, `Diff: 0: PASS: \(int=1\) == \(int=1\)\s+1: PASS: \(int=1\) == \(int=1\)\s+2: FAIL: \(int=2\) != \(int=1\)`))
2017 assert.Regexp(t, matchingExp, r)
2018 }
2019 }()
2020
2021 m := new(TestExampleImplementation)
2022 m.On("TheExampleMethod", 1, 1, 1).Return(1, nil).Once()
2023 m.On("TheExampleMethod", 2, 2, 2).Return(2, nil).Once()
2024
2025 m.TheExampleMethod(1, 1, 2)
2026 }
2027
2028 func TestClosestCallFavorsFirstMock(t *testing.T) {
2029 defer func() {
2030 if r := recover(); r != nil {
2031 diffRegExp := `Difference found in argument 0:\s+--- Expected\s+\+\+\+ Actual\s+@@ -2,4 \+2,4 @@\s+\(bool\) true,\s+- \(bool\) true,\s+- \(bool\) true\s+\+ \(bool\) false,\s+\+ \(bool\) false\s+}\s+`
2032 matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod7([]bool)`, `0: \[\]bool{true, false, false}`, `0: \[\]bool{true, true, true}`, diffRegExp))
2033 assert.Regexp(t, matchingExp, r)
2034 }
2035 }()
2036
2037 m := new(TestExampleImplementation)
2038 m.On("TheExampleMethod7", []bool{true, true, true}).Return(nil).Once()
2039 m.On("TheExampleMethod7", []bool{false, false, false}).Return(nil).Once()
2040
2041 m.TheExampleMethod7([]bool{true, false, false})
2042 }
2043
2044 func TestClosestCallUsesRepeatabilityToFindClosest(t *testing.T) {
2045 defer func() {
2046 if r := recover(); r != nil {
2047 diffRegExp := `Difference found in argument 0:\s+--- Expected\s+\+\+\+ Actual\s+@@ -1,4 \+1,4 @@\s+\(\[\]bool\) \(len=3\) {\s+- \(bool\) false,\s+- \(bool\) false,\s+\+ \(bool\) true,\s+\+ \(bool\) true,\s+\(bool\) false\s+`
2048 matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod7([]bool)`, `0: \[\]bool{true, true, false}`, `0: \[\]bool{false, false, false}`, diffRegExp))
2049 assert.Regexp(t, matchingExp, r)
2050 }
2051 }()
2052
2053 m := new(TestExampleImplementation)
2054 m.On("TheExampleMethod7", []bool{true, true, true}).Return(nil).Once()
2055 m.On("TheExampleMethod7", []bool{false, false, false}).Return(nil).Once()
2056
2057 m.TheExampleMethod7([]bool{true, true, true})
2058
2059
2060
2061 m.TheExampleMethod7([]bool{true, true, false})
2062 }
2063
2064 func TestClosestCallMismatchedArgumentValueInformation(t *testing.T) {
2065 defer func() {
2066 if r := recover(); r != nil {
2067 matchingExp := regexp.MustCompile(unexpectedCallRegex(`GetTime(int)`, "0: 1", "0: 999", `Diff: 0: FAIL: \(int=1\) != \(int=999\)`))
2068 assert.Regexp(t, matchingExp, r)
2069 }
2070 }()
2071
2072 m := new(timer)
2073 m.On("GetTime", 999).Return("SomeTime").Once()
2074
2075 _ = m.GetTime(1)
2076 }
2077
2078 func Test_isBetterMatchThanReturnsFalseIfCandidateCallIsNil(t *testing.T) {
2079 assert.False(t, matchCandidate{}.isBetterMatchThan(matchCandidate{}))
2080 }
2081
2082 func Test_isBetterMatchThanReturnsTrueIfOtherCandidateCallIsNil(t *testing.T) {
2083 assert.True(t, matchCandidate{call: &Call{}}.isBetterMatchThan(matchCandidate{}))
2084 }
2085
2086 func Test_isBetterMatchThanReturnsFalseIfDiffCountIsGreaterThanOther(t *testing.T) {
2087 assert.False(t, matchCandidate{call: &Call{}, diffCount: 2}.isBetterMatchThan(matchCandidate{call: &Call{}, diffCount: 1}))
2088 }
2089
2090 func Test_isBetterMatchThanReturnsTrueIfDiffCountIsLessThanOther(t *testing.T) {
2091 assert.True(t, matchCandidate{call: &Call{}, diffCount: 1}.isBetterMatchThan(matchCandidate{call: &Call{}, diffCount: 2}))
2092 }
2093
2094 func Test_isBetterMatchThanReturnsTrueIfRepeatabilityIsGreaterThanOther(t *testing.T) {
2095 assert.True(t, matchCandidate{call: &Call{Repeatability: 1}, diffCount: 1}.isBetterMatchThan(matchCandidate{call: &Call{Repeatability: -1}, diffCount: 1}))
2096 }
2097
2098 func Test_isBetterMatchThanReturnsFalseIfRepeatabilityIsLessThanOrEqualToOther(t *testing.T) {
2099 assert.False(t, matchCandidate{call: &Call{Repeatability: 1}, diffCount: 1}.isBetterMatchThan(matchCandidate{call: &Call{Repeatability: 1}, diffCount: 1}))
2100 }
2101
2102 func unexpectedCallRegex(method, calledArg, expectedArg, diff string) string {
2103 rMethod := regexp.QuoteMeta(method)
2104 return fmt.Sprintf(`\s+mock: Unexpected Method Call\s+-*\s+%s\s+%s\s+The closest call I have is:\s+%s\s+%s\s+%s`,
2105 rMethod, calledArg, rMethod, expectedArg, diff)
2106 }
2107
2108
2109 func ConcurrencyTestMethod(m *Mock) {
2110 m.Called()
2111 }
2112
2113 func TestConcurrentArgumentRead(t *testing.T) {
2114 methodUnderTest := func(c caller, u user) {
2115 go u.Use(c)
2116 c.Call()
2117 }
2118
2119 c := &mockCaller{}
2120 defer c.AssertExpectations(t)
2121
2122 u := &mockUser{}
2123 defer u.AssertExpectations(t)
2124
2125 done := make(chan struct{})
2126
2127 c.On("Call").Return().Once()
2128 u.On("Use", c).Return().Once().Run(func(args Arguments) { close(done) })
2129
2130 methodUnderTest(c, u)
2131 <-done
2132 }
2133
2134 type caller interface {
2135 Call()
2136 }
2137
2138 type mockCaller struct{ Mock }
2139
2140 func (m *mockCaller) Call() { m.Called() }
2141
2142 type user interface {
2143 Use(caller)
2144 }
2145
2146 type mockUser struct{ Mock }
2147
2148 func (m *mockUser) Use(c caller) { m.Called(c) }
2149
View as plain text