aws-smithy-mocks
A flexible mocking framework for testing clients generated by smithy-rs, including all packages of the AWS SDK for Rust.
This crate provides a simple yet powerful way to mock SDK client responses for testing purposes. It uses interceptors to return stub responses, allowing you to test both happy-path and error scenarios without mocking the entire client or using traits.
Key Features
- Simple API: Create mock rules with a fluent API using the [
mock!] macro - Flexible Response Types: Return modeled outputs, errors, or raw HTTP responses
- Request Matching: Match requests based on their properties
- Response Sequencing: Define sequences of responses for testing retry behavior
- Rule Modes: Control how rules are matched and applied
Basic Usage
use GetObjectOutput;
use Client;
use ByteStream;
use ;
async
Creating Rules
Rules are created using the [mock!] macro, which takes a client operation as an argument:
let rule = mock!
// Optional: Add a matcher to filter requests
.match_requests
// Add a response
.then_output;
Response Types
You can return different types of responses:
// Return a modeled output
let success_rule = mock!
.then_output;
// Return a modeled error
let error_rule = mock!
.then_error;
// Return an HTTP response
let http_rule = mock!
.then_http_response;
Response Sequences
For testing retry behavior or complex scenarios, you can define sequences of responses using the sequence builder API:
let retry_rule = mock!
.sequence
.http_status // First call returns 503
.http_status // Second call returns 503
.output // Third call succeeds
.build;
// With repetition using `times()`
let retry_rule = mock!
.sequence
.http_status
.times // First two calls return 503
.output // Third call succeeds
.build;
The sequence builder API provides a fluent interface for defining sequences of responses. After providing all responses in the sequence, the rule is considered exhausted.
Creating Mocked Clients
Use the [mock_client!] macro to create a client with your rules:
// Create a client with a single rule
let client = mock_client!;
// Create a client with multiple rules and a specific rule mode
let client = mock_client!;
// Create a client with additional configuration
let client = mock_client!;
Rule Modes
The [RuleMode] enum controls how rules are matched and applied:
RuleMode::Sequential: Rules are tried in order. When a rule is exhausted, the next rule is used.RuleMode::MatchAny: The first matching rule is used, regardless of order.
let interceptor = new
.rule_mode
.with_rule
.with_rule;
Testing Retry Behavior
The mocking framework supports testing retry behavior by allowing you to define sequences of responses:
async
Testing Different Responses Based on Request Parameters
async
This crate is part of the AWS SDK for Rust and the smithy-rs code generator.