summaryrefslogtreecommitdiff
path: root/vendor/github.com/golang/mock/sample/concurrent/concurrent_test.go
blob: e4b271eaec15070104ffae38f09c75ebe1217c00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package concurrent

import (
	"testing"

	"github.com/golang/mock/gomock"
	"golang.org/x/net/context"

	mock "github.com/golang/mock/sample/concurrent/mock"
)

func call(ctx context.Context, m Math) (int, error) {
	result := make(chan int)
	go func() {
		result <- m.Sum(1, 2)
		close(result)
	}()
	select {
	case r := <-result:
		return r, nil
	case <-ctx.Done():
		return 0, ctx.Err()
	}
}

// testConcurrentFails is expected to fail (and is disabled). It
// demonstrates how to use gomock.WithContext to interrupt the test
// from a different goroutine.
func testConcurrentFails(t *testing.T) {
	ctrl, ctx := gomock.WithContext(context.Background(), t)
	defer ctrl.Finish()
	m := mock.NewMockMath(ctrl)
	if _, err := call(ctx, m); err != nil {
		t.Error("call failed:", err)
	}
}

func TestConcurrentWorks(t *testing.T) {
	ctrl, ctx := gomock.WithContext(context.Background(), t)
	defer ctrl.Finish()
	m := mock.NewMockMath(ctrl)
	m.EXPECT().Sum(1, 2).Return(3)
	if _, err := call(ctx, m); err != nil {
		t.Error("call failed:", err)
	}
}