问题描述
我想测试用Go编写的gRPC服务。我使用的示例是 protobuf的定义如下: 我查找了一些示例,但我找不到任何关于如何在Go中实现gRPC服务的测试。 如果您想验证gRPC服务的实现是否符合您的期望,那么您可以编写标准单元测试并完全忽略网络。 b 例如,make 我可能已经把原始语法搞糊涂了,但这就是想法。 I'd like to test a gRPC service written in Go. The example I'm using is the Hello World server example from the grpc-go repo. The protobuf definition is as follows: And the type in the I've looked for examples but I couldn't find any on how to implement tests for a gRPC service in Go. If you want to verify that the implementation of the gRPC service does what you expect, then you can just write standard unit tests and ignore networking completely. For example, make I might've messed up the proto syntax a bit doing it from memory, but that's the idea. 这篇关于测试gRPC服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
语法=proto3;
包helloworld;
//问候服务定义。
服务Greeter {
//发送问候语
rpc SayHello(HelloRequest)返回(HelloReply){}
}
//请求消息包含用户的名字。
消息HelloRequest {
string name = 1;
}
//包含问候消息的响应消息
消息HelloReply {
string message = 1;
}
greeter_server $ c中的类型$ c> main是:
//服务器用于实现helloworld.GreeterServer。
类型服务器struct {}
// SayHello实现了helloworld.GreeterServer
func(s * server)SayHello(ctx context.Context,in * pb.HelloRequest)(* pb .HelloReply,error){
return& pb.HelloReply {Message:Hello+ in.Name},nil
}
greeter_server_test.go
:
s:= server {}
//设置测试用例
tests:= [] struct {
姓名字符串
希望字符串
} {
{
名称:world,
希望:Hello world,
},
{
名称:123,
想要:Hello 123,
},
}
for _,tt:=范围测试{
req:=& pb.HelloRequest {Name:tt.name}
resp,err:= s.SayHello(context.Background(),req)
if err! = nil {
t.Errorf(HelloTest(%v)出现意外错误)
}
if resp.Message!= tt.want {
t.Errorf( HelloText(%v)=%v,想要%v,tt.name,resp.Message,tt.want)
}
}
}
syntax = "proto3";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
greeter_server
main is:// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
greeter_server_test.go
:func HelloTest(t *testing.T) {
s := server{}
// set up test cases
tests := []struct{
name string
want string
} {
{
name: "world",
want: "Hello world",
},
{
name: "123",
want: "Hello 123",
},
}
for _, tt := range tests {
req := &pb.HelloRequest{Name: tt.name}
resp, err := s.SayHello(context.Background(), req)
if err != nil {
t.Errorf("HelloTest(%v) got unexpected error")
}
if resp.Message != tt.want {
t.Errorf("HelloText(%v)=%v, wanted %v", tt.name, resp.Message, tt.want)
}
}
}