| 1 |
package gomock_test |
| 2 |
|
| 3 |
//go:generate mockgen -destination mock_test.go -package gomock_test -source example_test.go |
| 4 |
|
| 5 |
import ( |
| 6 |
"fmt" |
| 7 |
"testing" |
| 8 |
"time" |
| 9 |
|
| 10 |
"github.com/golang/mock/gomock" |
| 11 |
) |
| 12 |
|
| 13 |
type Foo interface { |
| 14 |
Bar(string) string |
| 15 |
} |
| 16 |
|
| 17 |
func ExampleCall_DoAndReturn_latency() { |
| 18 |
t := &testing.T{} // provided by test |
| 19 |
ctrl := gomock.NewController(t) |
| 20 |
mockIndex := NewMockFoo(ctrl) |
| 21 |
|
| 22 |
mockIndex.EXPECT().Bar(gomock.Any()).DoAndReturn( |
| 23 |
// signature of anonymous function must have the same number of input and output arguments as the mocked method. |
| 24 |
func(arg string) string { |
| 25 |
time.Sleep(1 * time.Millisecond) |
| 26 |
return "I'm sleepy" |
| 27 |
}, |
| 28 |
) |
| 29 |
|
| 30 |
r := mockIndex.Bar("foo") |
| 31 |
fmt.Println(r) |
| 32 |
// Output: I'm sleepy |
| 33 |
} |
| 34 |
|
| 35 |
func ExampleCall_DoAndReturn_captureArguments() { |
| 36 |
t := &testing.T{} // provided by test |
| 37 |
ctrl := gomock.NewController(t) |
| 38 |
mockIndex := NewMockFoo(ctrl) |
| 39 |
var s string |
| 40 |
|
| 41 |
mockIndex.EXPECT().Bar(gomock.AssignableToTypeOf(s)).DoAndReturn( |
| 42 |
// signature of anonymous function must have the same number of input and output arguments as the mocked method. |
| 43 |
func(arg string) interface{} { |
| 44 |
s = arg |
| 45 |
return "I'm sleepy" |
| 46 |
}, |
| 47 |
) |
| 48 |
|
| 49 |
r := mockIndex.Bar("foo") |
| 50 |
fmt.Printf("%s %s", r, s) |
| 51 |
// Output: I'm sleepy foo |
| 52 |
} |