Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Commit 0214a04

Browse files
committed
Add example for Call.Do and Call.DoAndReturn
fixes issue #469 * include example of DoAndReturn in readme
1 parent 11d9cab commit 0214a04

File tree

2 files changed

+72
-2
lines changed

2 files changed

+72
-2
lines changed

README.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,11 +167,15 @@ func TestFoo(t *testing.T) {
167167

168168
m := NewMockFoo(ctrl)
169169

170-
// Does not make any assertions. Returns 101 when Bar is invoked with 99.
170+
// Does not make any assertions. Executes the anonymous functions and returns
171+
// its result when Bar is invoked with 99.
171172
m.
172173
EXPECT().
173174
Bar(gomock.Eq(99)).
174-
Return(101).
175+
DoAndReturn(func(_ int) int {
176+
time.Sleep(1*time.Second)
177+
return 101
178+
}).
175179
AnyTimes()
176180

177181
// Does not make any assertions. Returns 103 when Bar is invoked with 101.

gomock/doc_test.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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() {
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+
func() string {
19+
time.Sleep(1 * time.Second)
20+
return "I'm sleepy"
21+
},
22+
)
23+
}
24+
25+
func ExampleCall_DoAndReturn_captureArguments() {
26+
t := &testing.T{} // provided by test
27+
ctrl := gomock.NewController(t)
28+
mockIndex := mock_sample.NewMockIndex(ctrl)
29+
var s string
30+
31+
mockIndex.EXPECT().Get(gomock.AssignableToTypeOf(s)).DoAndReturn(
32+
// When capturing arguments the anonymous function should have the same signature as the mocked method.
33+
func(arg string) interface{} {
34+
time.Sleep(1 * time.Second)
35+
fmt.Println(arg)
36+
return "I'm sleepy"
37+
},
38+
)
39+
}
40+
41+
func ExampleCall_Do() {
42+
t := &testing.T{} // provided by test
43+
ctrl := gomock.NewController(t)
44+
mockIndex := mock_sample.NewMockIndex(ctrl)
45+
46+
mockIndex.EXPECT().Anon(gomock.Any()).Do(
47+
func() {
48+
time.Sleep(1 * time.Second)
49+
},
50+
)
51+
}
52+
53+
func ExampleCall_Do_captureArguments() {
54+
t := &testing.T{} // provided by test
55+
ctrl := gomock.NewController(t)
56+
mockIndex := mock_sample.NewMockIndex(ctrl)
57+
58+
var s string
59+
mockIndex.EXPECT().Anon(gomock.AssignableToTypeOf(s)).Do(
60+
// When capturing arguments the anonymous function should have the same signature as the mocked method.
61+
func(arg string) {
62+
time.Sleep(1 * time.Second)
63+
fmt.Println(arg)
64+
},
65+
)
66+
}

0 commit comments

Comments
 (0)