...

Source file src/github.com/golang/mock/sample/concurrent/concurrent_test.go

Documentation: github.com/golang/mock/sample/concurrent

     1  package concurrent
     2  
     3  import (
     4  	"testing"
     5  
     6  	"context"
     7  
     8  	"github.com/golang/mock/gomock"
     9  
    10  	mock "github.com/golang/mock/sample/concurrent/mock"
    11  )
    12  
    13  func call(ctx context.Context, m Math) (int, error) {
    14  	result := make(chan int)
    15  	go func() {
    16  		result <- m.Sum(1, 2)
    17  		close(result)
    18  	}()
    19  	select {
    20  	case r := <-result:
    21  		return r, nil
    22  	case <-ctx.Done():
    23  		return 0, ctx.Err()
    24  	}
    25  }
    26  
    27  // TestConcurrentFails is expected to fail (and is disabled). It
    28  // demonstrates how to use gomock.WithContext to interrupt the test
    29  // from a different goroutine.
    30  func TestConcurrentFails(t *testing.T) {
    31  	t.Skip("Test is expected to fail, remove skip to trying running yourself.")
    32  	ctrl, ctx := gomock.WithContext(context.Background(), t)
    33  	defer ctrl.Finish()
    34  	m := mock.NewMockMath(ctrl)
    35  	if _, err := call(ctx, m); err != nil {
    36  		t.Error("call failed:", err)
    37  	}
    38  }
    39  
    40  func TestConcurrentWorks(t *testing.T) {
    41  	ctrl, ctx := gomock.WithContext(context.Background(), t)
    42  	defer ctrl.Finish()
    43  	m := mock.NewMockMath(ctrl)
    44  	m.EXPECT().Sum(1, 2).Return(3)
    45  	if _, err := call(ctx, m); err != nil {
    46  		t.Error("call failed:", err)
    47  	}
    48  }
    49  

View as plain text