OSDN Git Service

new repo
[bytom/vapor.git] / vendor / google.golang.org / grpc / examples / helloworld / mock_helloworld / hw_mock_test.go
1 /*
2  *
3  * Copyright 2017 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 package mock_helloworld_test
20
21 import (
22         "fmt"
23         "testing"
24
25         "github.com/golang/mock/gomock"
26         "github.com/golang/protobuf/proto"
27         "golang.org/x/net/context"
28         helloworld "google.golang.org/grpc/examples/helloworld/helloworld"
29         hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld"
30 )
31
32 // rpcMsg implements the gomock.Matcher interface
33 type rpcMsg struct {
34         msg proto.Message
35 }
36
37 func (r *rpcMsg) Matches(msg interface{}) bool {
38         m, ok := msg.(proto.Message)
39         if !ok {
40                 return false
41         }
42         return proto.Equal(m, r.msg)
43 }
44
45 func (r *rpcMsg) String() string {
46         return fmt.Sprintf("is %s", r.msg)
47 }
48
49 func TestSayHello(t *testing.T) {
50         ctrl := gomock.NewController(t)
51         defer ctrl.Finish()
52         mockGreeterClient := hwmock.NewMockGreeterClient(ctrl)
53         req := &helloworld.HelloRequest{Name: "unit_test"}
54         mockGreeterClient.EXPECT().SayHello(
55                 gomock.Any(),
56                 &rpcMsg{msg: req},
57         ).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil)
58         testSayHello(t, mockGreeterClient)
59 }
60
61 func testSayHello(t *testing.T, client helloworld.GreeterClient) {
62         r, err := client.SayHello(context.Background(), &helloworld.HelloRequest{Name: "unit_test"})
63         if err != nil || r.Message != "Mocked Interface" {
64                 t.Errorf("mocking failed")
65         }
66         t.Log("Reply : ", r.Message)
67 }