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

Add example for Call.Do and Call.DoAndReturn #470

Merged
merged 2 commits into from
Aug 21, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,15 @@ func TestFoo(t *testing.T) {

m := NewMockFoo(ctrl)

// Does not make any assertions. Returns 101 when Bar is invoked with 99.
// Does not make any assertions. Executes the anonymous functions and returns
// its result when Bar is invoked with 99.
m.
EXPECT().
Bar(gomock.Eq(99)).
Return(101).
DoAndReturn(func(_ int) int {
time.Sleep(1*time.Second)
return 101
}).
AnyTimes()

// Does not make any assertions. Returns 103 when Bar is invoked with 101.
Expand Down
66 changes: 66 additions & 0 deletions gomock/doc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package gomock_test

import (
"fmt"
"testing"
"time"

"github.com/golang/mock/gomock"
mock_sample "github.com/golang/mock/sample/mock_user"
)

func ExampleCall_DoAndReturn() {
t := &testing.T{} // provided by test
ctrl := gomock.NewController(t)
mockIndex := mock_sample.NewMockIndex(ctrl)

mockIndex.EXPECT().Get(gomock.Any()).DoAndReturn(
func() string {
time.Sleep(1 * time.Second)
return "I'm sleepy"
},
)
}

func ExampleCall_DoAndReturn_captureArguments() {
t := &testing.T{} // provided by test
ctrl := gomock.NewController(t)
mockIndex := mock_sample.NewMockIndex(ctrl)
var s string
cvgw marked this conversation as resolved.
Show resolved Hide resolved

mockIndex.EXPECT().Get(gomock.AssignableToTypeOf(s)).DoAndReturn(
// When capturing arguments the anonymous function should have the same signature as the mocked method.
func(arg string) interface{} {
time.Sleep(1 * time.Second)
cvgw marked this conversation as resolved.
Show resolved Hide resolved
fmt.Println(arg)
return "I'm sleepy"
},
)
}

func ExampleCall_Do() {
cvgw marked this conversation as resolved.
Show resolved Hide resolved
t := &testing.T{} // provided by test
ctrl := gomock.NewController(t)
mockIndex := mock_sample.NewMockIndex(ctrl)

mockIndex.EXPECT().Anon(gomock.Any()).Do(
func() {
time.Sleep(1 * time.Second)
},
)
}

func ExampleCall_Do_captureArguments() {
t := &testing.T{} // provided by test
ctrl := gomock.NewController(t)
mockIndex := mock_sample.NewMockIndex(ctrl)

var s string
mockIndex.EXPECT().Anon(gomock.AssignableToTypeOf(s)).Do(
// When capturing arguments the anonymous function should have the same signature as the mocked method.
func(arg string) {
time.Sleep(1 * time.Second)
fmt.Println(arg)
},
)
}