server: Index | Examples | Files

package grpctest

import ""

Package grpctest provides a test server for unit tests that use gRPC.


package main

import (


    gomapb ""
    pb ""

// MyServer is fake execlog server.
type MyServer struct {
    Req  *gomapb.SaveLogReq
    Resp *gomapb.SaveLogResp
    Err  error

func (s *MyServer) SaveLog(ctx context.Context, req *gomapb.SaveLogReq) (*gomapb.SaveLogResp, error) {
    s.Req = req
    return s.Resp, s.Err

func main() {
    srv := grpc.NewServer()
    s := &MyServer{
        Resp: &gomapb.SaveLogResp{},
    pb.RegisterLogServiceServer(srv, s)
    addr, stop, err := grpctest.StartServer(srv)
    if err != nil {
        fmt.Printf("error creating test server: %v\n", err)
    defer stop()

    conn, err := grpc.Dial(addr, grpc.WithInsecure())
    if err != nil {
        fmt.Printf("error connecting to %s: %v\n", addr, err)
    defer conn.Close()
    client := pb.NewLogServiceClient(conn)
    ctx := context.Background()
    resp, err := client.SaveLog(ctx, &gomapb.SaveLogReq{})
    if err != nil {
        fmt.Printf("SaveLog()=%v, %v; want nil error\n", resp, err)



Package Files


func StartServer Uses

func StartServer(server *grpc.Server) (addr string, stop func(), err error)

StartServer instantiates a gRPC server suitable for unit tests, and returns the server address the client can use to connect and a stop function that must be called if err is nil to stop the server and cleanup resources.

Package grpctest imports 3 packages (graph). Updated 2020-10-27. Refresh now. Tools for package owners.