Crate wiremock_grpc

Crate wiremock_grpc 

Source
Expand description

§wiremock-grpc

gRPC mocking to test Rust applications.

This crate provides an easy way to mock gRPC services in your tests, allowing you to test client code without running actual gRPC servers. It features a type-safe API for defining mock behaviors and verifying requests.

§Quick Start

Use the generate_svc! macro to create a mock server:

use wiremock_grpc::{generate_svc, MockBuilder};
use tonic::Code;

// Generate a mock server (make sure the package, service and the rpc names are exactly as they are named in the proto files)
generate_svc! {
    package hello;
    service Greeter {
        SayHello,
        WeatherInfo,
    }
}

#[tokio::test]
async fn test_grpc_service() {
    // Start the mock server
    let mut server = GreeterMockServer::start_default().await;

    // Set up a mock response
    server.setup(
        MockBuilder::when()
            .path_say_hello()  // method generated by generate_svc macro (for each item under "service" block)
            .then()
            .return_status(Code::Ok)
            .return_body(|| HelloReply {
                message: "Hello from mock!".into(),
            }),
    );

    // Connect your client and test
    let channel = tonic::transport::Channel::from_shared(
        format!("http://[::1]:{}", server.address().port())
    )
    .unwrap()
    .connect()
    .await
    .unwrap();

    let mut client = GreeterClient::new(channel);
    let response = client
        .say_hello(HelloRequest { name: "World".into() })
        .await
        .unwrap();

    assert_eq!("Hello from mock!", response.into_inner().message);
}

§Features

  • Type-safe API: Generate type-safe path_* methods for each RPC using generate_svc!
  • Header Matching: Match requests based on gRPC metadata/headers
  • Status Codes: Return any gRPC status code
  • Custom Bodies: Return custom response bodies with closures
  • Request Verification: Track invocations and verify calls were made
  • Flexible Binding: Start servers on random ports, specific ports, or custom addresses

§Custom Server Name

You can specify a custom name for the generated server:

generate_svc! {
    package hello;
    service Greeter as MyCustomServer {
        SayHello,
    }
}
let server = MyCustomServer::start_default().await;

§Header Matching

Match requests based on gRPC metadata:

server.setup(
    MockBuilder::when()
        .path_say_hello()
        .header("x-session-id", "abc123")
        .then()
        .return_body(|| HelloReply {
            message: "Authenticated response".into(),
        }),
);

§What generate_svc! Generates

The macro generates:

  • {ServiceName}MockServer - Mock server struct with:
    • start_default() - Start on a random available port
    • start(port) - Start on a specific port
    • start_with_addr(addr) - Start on a specific address
    • setup() - Configure mock behaviors
    • address() - Get the server’s bind address
  • {ServiceName}TypeSafeExt - Extension trait adding path_{method_name} methods to WhenBuilder

§Main Types

  • MockBuilder - Build mock behaviors with when() and then() pattern
  • WhenBuilder - Configure request matching (path, headers, etc.)
  • Then - Configure response behavior (status, body, headers)
  • GrpcServer - The underlying mock server (dereferenced by generated servers)

Re-exports§

pub extern crate http_body;
pub extern crate tonic;
pub use wiremock::builder::MockBuilder;
pub use wiremock::builder::Mountable;
pub use wiremock::builder::Then;
pub use wiremock::builder::WhenBuilder;
pub use wiremock::grpc_server::GrpcServer;
pub use wiremock::tonic_ext;

Modules§

wiremock

Macros§

generateDeprecated
Generate mock server code for the given prefix and type.
generate_svc
Generates a complete mock gRPC server with RPC method builders.