Home >Backend Development >Golang >How Can I Efficiently Test gRPC Services in Go Without Using Real Ports?

How Can I Efficiently Test gRPC Services in Go Without Using Real Ports?

DDD
DDDOriginal
2024-12-17 18:12:15428browse

How Can I Efficiently Test gRPC Services in Go Without Using Real Ports?

Testing a gRPC Service

Testing gRPC services written in Go can be achieved using the google.golang.org/grpc/test/bufconn package. This package facilitates testing streaming RPCs without the reliance on real port numbers.

Example:

To test the provided Hello World server:

package main

import (
    "context"
    "log"
    "testing"

    pb "helloworld"

    "github.com/golang/protobuf/ptypes/empty"

    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
    "google.golang.org/grpc/test/bufconn"
)

const bufSize = 1024 * 1024

var lis *bufconn.Listener

func init() {
    lis = bufconn.Listen(bufSize)
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    go func() {
        if err := s.Serve(lis); err != nil {
            log.Fatalf("Server exited with error: %v", err)
        }
    }()
}

func bufDialer(context.Context, string) (net.Conn, error) {
    return lis.Dial()
}

func TestSayHello(t *testing.T) {
    ctx := context.Background()
    conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
    if err != nil {
        t.Fatalf("Failed to dial bufnet: %v", err)
    }
    defer conn.Close()
    client := pb.NewGreeterClient(conn)
    resp, err := client.SayHello(ctx, &pb.HelloRequest{"Dr. Seuss"})
    if err != nil {
        t.Fatalf("SayHello failed: %v", err)
    }
    log.Printf("Response: %+v", resp)
    // Test for output here.
}

Benefits:

  • Avoids real port usage during testing
  • Provides network behavior in a controlled environment
  • Simulates real-world usage patterns for testing streaming RPCs

The above is the detailed content of How Can I Efficiently Test gRPC Services in Go Without Using Real Ports?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn