Learn how to stub real client implementations to inject a mock for unit testing. Using a mock client with the Google Cloud Client Libraries for Rust lets you write controlled, reliable unit tests that don't make network calls or incur billing charges.
Dependencies
There are several mocking frameworks available for Rust. This guide uses
mockall. Add it as a development dependency:
cargo add --dev mockall
Additionally, this guide uses the Speech client to make
examples easier to follow (but these concepts apply to all clients).
Add the required dependencies to your Cargo.toml file:
cargo add google-cloud-speech-v2 google-cloud-lro
Mock a client
To test your code with a mock client, you define a mock struct, configure its expected behavior for your test scenario, and then inject that mock into your application logic. The following example demonstrates this workflow.
First, add use statements to simplify the code:
Assume the application has a function that uses the Speech
client to call GetRecognizer, setting the name field of the request,
and process the server response.
You can test how the application handles different responses from the service.
Next, define the mock struct. This struct implements the
speech::stub::Speech trait.
Create an instance of the mock. Note that the
mockall::mock! macro prepends a Mock prefix to the name of the
previously defined struct.
Set expectations on the mock. For example, expect the code to call
GetRecognizer with a particular name and simulate a successful response
from the service.
Create a Speech client using the mock:
Call the function:
Verify the results:
Simulate errors
Simulating errors is similar to simulating successes. To simulate an error, modify the result returned by the mock.
A client built with from_stub() does not have an internal retry loop; it
returns all errors from the stub directly to the application.
Next steps
To view the complete code from this guide, see the source file in the google-cloud-rust repository on GitHub.