gRPC Mocking with grpc-mock and testify: A Practical Guide

gRPC Mocking with grpc-mock and testify: A Practical Guide

Testing gRPC clients is harder than testing REST clients. You can't just stub an HTTP endpoint — you need a real gRPC server interface or a mock implementation that satisfies the generated client interface. This guide covers the three main mocking strategies for gRPC in Go: manual mocks, testify-based mocks, and grpc-mock for black-box testing.

Why Mock gRPC Services?

When testing code that calls a gRPC service, you need to:

  • Test your client logic without depending on a live server
  • Simulate error conditions that are hard to reproduce in real servers
  • Control response timing (latency, streaming pace)
  • Verify that your code sends the right requests
  • Run tests without external dependencies

Mocking strategies range from simple (manual interface implementations) to sophisticated (grpc-mock server that validates expectations).

Strategy 1: Manual Interface Mocks

The simplest approach. Generated gRPC code includes client interfaces you can implement directly.

Given this proto:

service OrderService {
  rpc CreateOrder (CreateOrderRequest) returns (OrderResponse);
  rpc GetOrderStatus (OrderStatusRequest) returns (stream OrderEvent);
}

The generated client interface looks like:

type OrderServiceClient interface {
    CreateOrder(ctx context.Context, in *CreateOrderRequest, opts ...grpc.CallOption) (*OrderResponse, error)
    GetOrderStatus(ctx context.Context, in *OrderStatusRequest, opts ...grpc.CallOption) (OrderService_GetOrderStatusClient, error)
}

Write a manual mock:

type mockOrderClient struct {
    createOrderFn    func(ctx context.Context, req *pb.CreateOrderRequest) (*pb.OrderResponse, error)
    getOrderStatusFn func(ctx context.Context, req *pb.OrderStatusRequest) (pb.OrderService_GetOrderStatusClient, error)
}

func (m *mockOrderClient) CreateOrder(ctx context.Context, in *pb.CreateOrderRequest, opts ...grpc.CallOption) (*pb.OrderResponse, error) {
    return m.createOrderFn(ctx, in)
}

func (m *mockOrderClient) GetOrderStatus(ctx context.Context, in *pb.OrderStatusRequest, opts ...grpc.CallOption) (pb.OrderService_GetOrderStatusClient, error) {
    return m.getOrderStatusFn(ctx, in)
}

Use it in tests:

func TestOrderProcessor_CreateOrder(t *testing.T) {
    mock := &mockOrderClient{
        createOrderFn: func(ctx context.Context, req *pb.CreateOrderRequest) (*pb.OrderResponse, error) {
            // Verify request contents
            assert.Equal(t, "product-123", req.ProductId)
            assert.Equal(t, int32(2), req.Quantity)
            
            return &pb.OrderResponse{
                OrderId: "ord-789",
                Status:  "CONFIRMED",
            }, nil
        },
    }
    
    processor := NewOrderProcessor(mock)
    
    result, err := processor.PlaceOrder(context.Background(), "product-123", 2)
    require.NoError(t, err)
    assert.Equal(t, "ord-789", result.OrderID)
    assert.Equal(t, "CONFIRMED", result.Status)
}

Pros: Simple, no dependencies, full control. Cons: Boilerplate, no automatic call verification.

Strategy 2: testify/mock for gRPC

testify/mock adds call tracking, argument matchers, and return value chaining. Combine it with mockery to auto-generate the mock boilerplate.

Install mockery:

go install github.com/vektra/mockery/v2@latest

Generate mocks from your gRPC client interface:

mockery --name=OrderServiceClient --srcpkg=example.com/proto/order/v1 --output=./mocks

This generates mocks/OrderServiceClient.go with a testify mock implementation.

Using Generated testify Mocks

package order_test

import (
    "context"
    "testing"
    
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/mock"
    "github.com/stretchr/testify/require"
    
    pb "example.com/proto/order/v1"
    "example.com/order/mocks"
)

func TestOrderProcessor_CreateOrder_WithTestify(t *testing.T) {
    mockClient := mocks.NewOrderServiceClient(t)
    
    // Set up expectations
    mockClient.On("CreateOrder",
        mock.Anything, // context
        &pb.CreateOrderRequest{
            ProductId: "product-123",
            Quantity:  2,
        },
        mock.Anything, // grpc.CallOption varargs
    ).Return(&pb.OrderResponse{
        OrderId: "ord-789",
        Status:  "CONFIRMED",
    }, nil)
    
    processor := NewOrderProcessor(mockClient)
    
    result, err := processor.PlaceOrder(context.Background(), "product-123", 2)
    require.NoError(t, err)
    assert.Equal(t, "ord-789", result.OrderID)
    
    // testify/mock automatically verifies all expected calls were made
    mockClient.AssertExpectations(t)
}

Using Argument Matchers

For flexible matching when you don't care about exact values:

func TestOrderProcessor_CreateOrder_AnyProduct(t *testing.T) {
    mockClient := mocks.NewOrderServiceClient(t)
    
    // Match any CreateOrderRequest
    mockClient.On("CreateOrder",
        mock.Anything,
        mock.MatchedBy(func(req *pb.CreateOrderRequest) bool {
            return req.Quantity > 0 && req.ProductId != ""
        }),
        mock.Anything,
    ).Return(&pb.OrderResponse{
        OrderId: "ord-auto",
        Status:  "CONFIRMED",
    }, nil)
    
    processor := NewOrderProcessor(mockClient)
    
    _, err := processor.PlaceOrder(context.Background(), "any-product", 5)
    require.NoError(t, err)
    
    mockClient.AssertExpectations(t)
}

Simulating Errors with testify

func TestOrderProcessor_HandleServiceUnavailable(t *testing.T) {
    mockClient := mocks.NewOrderServiceClient(t)
    
    // Simulate service unavailable
    mockClient.On("CreateOrder",
        mock.Anything,
        mock.Anything,
        mock.Anything,
    ).Return(nil, status.Errorf(codes.Unavailable, "service temporarily unavailable"))
    
    processor := NewOrderProcessor(mockClient)
    
    _, err := processor.PlaceOrder(context.Background(), "product-123", 1)
    require.Error(t, err)
    
    // Verify your processor correctly handles this error
    assert.Contains(t, err.Error(), "service unavailable")
    
    mockClient.AssertExpectations(t)
}

Testing Retry Logic

testify makes it easy to test retry behavior by sequencing return values:

func TestOrderProcessor_RetriesOnTransientFailure(t *testing.T) {
    mockClient := mocks.NewOrderServiceClient(t)
    
    // First call fails with UNAVAILABLE, second call succeeds
    mockClient.On("CreateOrder", mock.Anything, mock.Anything, mock.Anything).
        Return(nil, status.Errorf(codes.Unavailable, "temporary error")).
        Once()
    
    mockClient.On("CreateOrder", mock.Anything, mock.Anything, mock.Anything).
        Return(&pb.OrderResponse{OrderId: "ord-789", Status: "CONFIRMED"}, nil).
        Once()
    
    processor := NewOrderProcessorWithRetry(mockClient, 3)
    
    result, err := processor.PlaceOrder(context.Background(), "product-123", 1)
    require.NoError(t, err)
    assert.Equal(t, "ord-789", result.OrderID)
    
    // Verify both calls were made (one retry happened)
    mockClient.AssertNumberOfCalls(t, "CreateOrder", 2)
    mockClient.AssertExpectations(t)
}

Mocking Streaming RPCs with testify

Streaming RPCs require mocking the stream interface, not just the method:

// Mock the stream interface
type mockOrderStatusStream struct {
    mock.Mock
    events []*pb.OrderEvent
    index  int
}

func (m *mockOrderStatusStream) Recv() (*pb.OrderEvent, error) {
    if m.index >= len(m.events) {
        return nil, io.EOF
    }
    event := m.events[m.index]
    m.index++
    return event, nil
}

func (m *mockOrderStatusStream) Header() (metadata.MD, error) { return nil, nil }
func (m *mockOrderStatusStream) Trailer() metadata.MD         { return nil }
func (m *mockOrderStatusStream) CloseSend() error             { return nil }
func (m *mockOrderStatusStream) Context() context.Context     { return context.Background() }
func (m *mockOrderStatusStream) SendMsg(v interface{}) error  { return nil }
func (m *mockOrderStatusStream) RecvMsg(v interface{}) error  { return nil }

func TestOrderProcessor_TrackOrderStatus(t *testing.T) {
    streamMock := &mockOrderStatusStream{
        events: []*pb.OrderEvent{
            {EventType: "PROCESSING", OrderId: "ord-789"},
            {EventType: "SHIPPED", OrderId: "ord-789", TrackingId: "1Z999..."},
            {EventType: "DELIVERED", OrderId: "ord-789"},
        },
    }
    
    mockClient := mocks.NewOrderServiceClient(t)
    mockClient.On("GetOrderStatus",
        mock.Anything,
        &pb.OrderStatusRequest{OrderId: "ord-789"},
        mock.Anything,
    ).Return(streamMock, nil)
    
    processor := NewOrderProcessor(mockClient)
    
    statuses, err := processor.TrackOrder(context.Background(), "ord-789")
    require.NoError(t, err)
    
    require.Len(t, statuses, 3)
    assert.Equal(t, "PROCESSING", statuses[0])
    assert.Equal(t, "SHIPPED", statuses[1])
    assert.Equal(t, "DELIVERED", statuses[2])
    
    mockClient.AssertExpectations(t)
}

Strategy 3: grpc-mock for Black-Box Testing

grpc-mock runs a real gRPC server that matches requests against expectations. It's useful when:

  • You want to test at the network level (e.g., testing with TLS, interceptors)
  • You're testing code that creates its own gRPC connections
  • You need to share mock servers across multiple test processes

Install grpc-mock:

npm install @grpc/grpc-js grpc-mock

Or use the Go equivalent with gripmock:

go install github.com/tokopedia/gripmock@latest

Using gripmock

Start a mock gRPC server from your proto files:

# Start gripmock with your proto
gripmock --stub=./stubs proto/order/v1/order.proto

Create stub files in ./stubs/:

{
  "service": "OrderService",
  "method": "CreateOrder",
  "input": {
    "equals": {
      "product_id": "product-123",
      "quantity": 2
    }
  },
  "output": {
    "data": {
      "order_id": "ord-789",
      "status": "CONFIRMED"
    }
  }
}

Now your real gRPC client can connect to the gripmock server at localhost:4770. This tests the actual gRPC connection, serialization, and deserialization:

func TestOrderClient_Integration_WithGripmock(t *testing.T) {
    // gripmock is running at localhost:4770
    conn, err := grpc.Dial("localhost:4770", grpc.WithInsecure())
    require.NoError(t, err)
    defer conn.Close()
    
    client := pb.NewOrderServiceClient(conn)
    
    resp, err := client.CreateOrder(context.Background(), &pb.CreateOrderRequest{
        ProductId: "product-123",
        Quantity:  2,
    })
    require.NoError(t, err)
    assert.Equal(t, "ord-789", resp.OrderId)
    assert.Equal(t, "CONFIRMED", resp.Status)
}

gripmock in Docker for CI

# docker-compose.test.yml
services:
  order-mock:
    image: tkpd/gripmock:latest
    ports:
      - "4770:4770"
      - "4771:4771"
    volumes:
      - ./proto:/proto
      - ./stubs:/stub
    command: --stub=/stub /proto/order/v1/order.proto
# .github/workflows/test.yml
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      order-mock:
        image: tkpd/gripmock:latest
        ports:
          - 4770:4770
        volumes:
          - ${{ github.workspace }}/stubs:/stub
          - ${{ github.workspace }}/proto:/proto
    steps:
      - uses: actions/checkout@v4
      - run: go test ./...

Choosing the Right Strategy

Strategy Best for Avoid when
Manual mocks Simple, few methods Many methods, lots of boilerplate
testify/mock + mockery Call verification, retry testing Complex streaming scenarios
gripmock Network-level testing, CI/CD Unit tests (too heavy)

A common pattern: use testify mocks for unit tests, gripmock for integration tests.

Verifying Your Mocks Don't Lie

Mock drift — when mocks diverge from the real service — is a silent killer. Prevent it:

  1. Generate mocks from proto definitions, not by hand
  2. Run contract tests against real servers in addition to mock-based unit tests
  3. Use buf to validate protos before regenerating mocks
  4. Lock mock generation in CI — regenerate and verify no diff
# CI step: verify mocks are up to date
mockery --all --output=./mocks
git diff --exit-code ./mocks

If this fails, someone updated the proto without regenerating mocks.

Key Takeaways

  • Start with manual mocks for simple cases — no dependency overhead
  • Use testify/mock + mockery for call verification and retry logic testing
  • Use gripmock for integration tests that need a real gRPC server
  • Always mock at the interface level — not the concrete type
  • Mock streaming RPCs by implementing the stream interface, not just the client method
  • Guard against mock drift with CI regeneration checks

Read more

Start now free