gRPC mocking to test Rust applications.
Use the generate_svc! macro to generate a mock server with type-safe RPC methods:
use wiremock_grpc::{generate_svc, MockBuilder};
use tonic::Code;
generate_svc! {
package hello;
service Greeter {
SayHello,
WeatherInfo,
// ... add the name of other rpc methods here.
}
}
#[tokio::test]
async fn test_grpc() {
// GreeterMockServer is generated by the macro
let mut server = GreeterMockServer::start_default().await;
// Use type-safe path_* methods
server.setup(
MockBuilder::when()
.path_say_hello()
.then()
.return_status(Code::Ok)
.return_body(|| HelloReply {
message: "Hello!".into(),
}),
);
// Connect your client
let channel = tonic::transport::Channel::from_shared(
format!("http://[::1]:{}", server.address().port())
)
.unwrap()
.connect()
.await
.unwrap();
let mut client = GreeterClient::new(channel);
// Make requests
let response = client
.say_hello(HelloRequest { name: "World".into() })
.await
.unwrap();
assert_eq!("Hello!", response.into_inner().message);
}You can specify a custom name for the generated server using as:
generate_svc! {
package hello;
service Greeter as MyMockServer {
SayHello,
}
}
let server = MyMockServer::start_default().await;server.setup(
MockBuilder::when()
.path_weather_info()
.header("x-session-id", "abc123")
.then()
.return_body(|| WeatherReply {
weather: "Sunny".into(),
}),
);You can also use the string-based API for paths:
server.setup(
MockBuilder::when()
.path("/hello.Greeter/SayHello")
.then()
.return_body(|| HelloReply {
message: "Hello!".into(),
}),
);The generate_svc! macro generates:
{ServiceName}MockServer(or custom name) - the mock server struct withstart_default(),start(port), andstart_with_addr(addr)methods{ServiceName}TypeSafeExttrait - extension trait forWhenBuilderwithpath_{method_name}methods
- wiremock-grpc/ - Main crate published to crates.io
- wiremock-grpc-macros/ - Proc macro crate for type-safe RPC methods. You do not need to depend on it directly.