|
| 1 | +package gomock_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/golang/mock/gomock" |
| 9 | + mock_sample "github.com/golang/mock/sample/mock_user" |
| 10 | +) |
| 11 | + |
| 12 | +func ExampleCall_DoAndReturn_latency() { |
| 13 | + t := &testing.T{} // provided by test |
| 14 | + ctrl := gomock.NewController(t) |
| 15 | + mockIndex := mock_sample.NewMockIndex(ctrl) |
| 16 | + |
| 17 | + mockIndex.EXPECT().Get(gomock.Any()).DoAndReturn( |
| 18 | + // signature of anonymous function must have the same number of input and output arguments as the mocked method. |
| 19 | + func(arg string) string { |
| 20 | + time.Sleep(1 * time.Millisecond) |
| 21 | + return "I'm sleepy" |
| 22 | + }, |
| 23 | + ) |
| 24 | + |
| 25 | + r := mockIndex.Get("foo") |
| 26 | + fmt.Println(r) |
| 27 | + // Output: I'm sleepy |
| 28 | +} |
| 29 | + |
| 30 | +func ExampleCall_DoAndReturn_captureArguments() { |
| 31 | + t := &testing.T{} // provided by test |
| 32 | + ctrl := gomock.NewController(t) |
| 33 | + mockIndex := mock_sample.NewMockIndex(ctrl) |
| 34 | + var s string |
| 35 | + |
| 36 | + mockIndex.EXPECT().Get(gomock.AssignableToTypeOf(s)).DoAndReturn( |
| 37 | + // signature of anonymous function must have the same number of input and output arguments as the mocked method. |
| 38 | + func(arg string) interface{} { |
| 39 | + s = arg |
| 40 | + return "I'm sleepy" |
| 41 | + }, |
| 42 | + ) |
| 43 | + |
| 44 | + r := mockIndex.Get("foo") |
| 45 | + fmt.Printf("%s %s", r, s) |
| 46 | + // Output: I'm sleepy foo |
| 47 | +} |
| 48 | + |
| 49 | +func ExampleCall_Do_latency() { |
| 50 | + t := &testing.T{} // provided by test |
| 51 | + ctrl := gomock.NewController(t) |
| 52 | + mockIndex := mock_sample.NewMockIndex(ctrl) |
| 53 | + |
| 54 | + mockIndex.EXPECT().Anon(gomock.Any()).Do( |
| 55 | + // signature of anonymous function must have the same number of input and output arguments as the mocked method. |
| 56 | + func(_ string) { |
| 57 | + fmt.Println("sleeping") |
| 58 | + time.Sleep(1 * time.Millisecond) |
| 59 | + }, |
| 60 | + ) |
| 61 | + |
| 62 | + mockIndex.Anon("foo") |
| 63 | + // Output: sleeping |
| 64 | +} |
| 65 | + |
| 66 | +func ExampleCall_Do_captureArguments() { |
| 67 | + t := &testing.T{} // provided by test |
| 68 | + ctrl := gomock.NewController(t) |
| 69 | + mockIndex := mock_sample.NewMockIndex(ctrl) |
| 70 | + |
| 71 | + var s string |
| 72 | + mockIndex.EXPECT().Anon(gomock.AssignableToTypeOf(s)).Do( |
| 73 | + // signature of anonymous function must have the same number of input and output arguments as the mocked method. |
| 74 | + func(arg string) { |
| 75 | + s = arg |
| 76 | + }, |
| 77 | + ) |
| 78 | + |
| 79 | + mockIndex.Anon("foo") |
| 80 | + fmt.Println(s) |
| 81 | + // Output: foo |
| 82 | +} |
0 commit comments