The Cloud Client Libraries for Rust let you stub real client implementations and inject a mock for unit testing. Using a mock client lets you write controlled, reliable unit tests that don't make network calls or incur billed charges.
Before you begin
Before running the code in this document, follow Get started with Rust to install Rust and set up a Cargo project.
Dependencies
This document uses the mockall crate as its mocking framework and
the Speech client from Speech-to-Text to illustrate the
workflow, though the same pattern applies to other generated clients.
Add the client library and google-cloud-gax to your Cargo.toml file:
cargo add google-cloud-speech-v2 google-cloud-gax
Add mockall and tokio as development dependencies:
cargo add --dev mockall
cargo add --dev tokio --features macros,rt-multi-thread
Mock a client
To test your code without network calls, implement the service's stub trait on
a mock struct and configure its expectations. Then construct a client with
from_stub and pass it to your application function:
Add
usealiases to shorten crate names:Write an application function that accepts a reference to the
Speechclient, callsget_recognizer, and processes the server response:Define a mock struct that implements the
speech::stub::Speechtrait usingmockall::mock!:In your test, create an instance of the mock. The
mockall::mock!macro prependsMockto the struct name to createMockSpeech:Configure expectations on the mock to validate incoming request fields and return a simulated
Recognizerresponse:Construct a
Speechclient from the mock usingSpeech::from_stub:Call the application function with the mocked client:
Verify the returned value:
Simulate errors
To test error handling, configure the mock expectation to return an Err
constructed with Error::service:
Complete code
The following example combines both the success and error unit tests into a complete test module:
Run cargo test to execute the unit tests:
cargo test