You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

71 lines
1.9 KiB

  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. package mock_helloworld_test
  19. import (
  20. "context"
  21. "fmt"
  22. "testing"
  23. "time"
  24. "github.com/golang/mock/gomock"
  25. "github.com/golang/protobuf/proto"
  26. helloworld "google.golang.org/grpc/examples/helloworld/helloworld"
  27. hwmock "google.golang.org/grpc/examples/helloworld/mock_helloworld"
  28. )
  29. // rpcMsg implements the gomock.Matcher interface
  30. type rpcMsg struct {
  31. msg proto.Message
  32. }
  33. func (r *rpcMsg) Matches(msg interface{}) bool {
  34. m, ok := msg.(proto.Message)
  35. if !ok {
  36. return false
  37. }
  38. return proto.Equal(m, r.msg)
  39. }
  40. func (r *rpcMsg) String() string {
  41. return fmt.Sprintf("is %s", r.msg)
  42. }
  43. func TestSayHello(t *testing.T) {
  44. ctrl := gomock.NewController(t)
  45. defer ctrl.Finish()
  46. mockGreeterClient := hwmock.NewMockGreeterClient(ctrl)
  47. req := &helloworld.HelloRequest{Name: "unit_test"}
  48. mockGreeterClient.EXPECT().SayHello(
  49. gomock.Any(),
  50. &rpcMsg{msg: req},
  51. ).Return(&helloworld.HelloReply{Message: "Mocked Interface"}, nil)
  52. testSayHello(t, mockGreeterClient)
  53. }
  54. func testSayHello(t *testing.T, client helloworld.GreeterClient) {
  55. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  56. defer cancel()
  57. r, err := client.SayHello(ctx, &helloworld.HelloRequest{Name: "unit_test"})
  58. if err != nil || r.Message != "Mocked Interface" {
  59. t.Errorf("mocking failed")
  60. }
  61. t.Log("Reply : ", r.Message)
  62. }