rust-api-test-harness
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust API Test Harness
Rust API 测试框架
Use this skill to make Rust API work test-first, reproducible, and CI-ready.
Prefer black-box tests that exercise the service through HTTP and verify
observable behavior rather than reaching through framework internals.
使用此 skill,让 Rust API 工作流做到测试优先、可复现并适合 CI。
优先编写黑盒测试,通过 HTTP 调用服务并验证可观察行为,而不是深入框架内部进行测试。
Core Workflow
核心工作流
- Inspect the project first: , workspace layout, existing
Cargo.toml,src/main.rs, router/startup modules,src/lib.rs, migrations, Docker Compose, and CI workflows.tests/ - Find the application boundary. Extract startup code into a reusable function if needed so tests can bind a random local port and pass explicit state.
- Write or update an integration test before changing behavior. Put API tests
under unless the project already has a clear convention.
tests/ - Create a helper that starts the service once per test case, captures the base URL, and owns any disposable test resources.
spawn_app - Exercise the public HTTP contract with , not framework-specific request objects, unless the project intentionally uses in-process tests.
reqwest - Isolate state. Use real dependencies when behavior depends on their semantics: Postgres for SQL behavior, a mock HTTP server for external APIs, and unique resource names per test.
- Keep test helpers as production-quality code. Give failures useful messages, hide boilerplate behind small helper methods, and avoid sleeps when readiness can be observed.
- Run the local verification script or equivalent cargo commands before finishing.
- 首先检查项目:、工作区布局、现有的
Cargo.toml、src/main.rs、路由/启动模块、src/lib.rs、migrations、Docker Compose 和 CI workflows。tests/ - 确定应用边界。必要时将启动代码提取为可复用函数, 使测试能够绑定随机本地端口并传入显式状态。
- 在修改行为之前编写或更新集成测试。除非项目已有明确的约定,
否则将 API 测试放在 下。
tests/ - 创建一个 helper,在每个测试用例中启动一次服务, 获取 base URL,并管理所有一次性测试资源。
spawn_app - 使用 测试公共 HTTP 契约,而不是使用特定框架的 request objects,除非项目有意采用进程内测试。
reqwest - 隔离状态。当行为依赖于某些依赖项的语义时,使用真实依赖: 涉及 SQL 行为时使用 Postgres,外部 API 使用 mock HTTP 服务器, 并为每个测试使用唯一的资源名称。
- 将测试 helper 保持为生产级代码。让失败信息具有实际帮助, 将样板代码封装在小型辅助方法中;如果可以观测就绪状态, 则避免使用 sleep。
- 完成后运行本地验证脚本或等效的 cargo 命令。
Startup Shape
启动结构
Prefer a startup function that accepts infrastructure instead of creating it
inside the handler module. Actix can listen on a synchronous
:
std::net::TcpListenerrust
pub fn run(
listener: std::net::TcpListener,
app_state: AppState,
) -> Result<actix_web::dev::Server, std::io::Error> {
let state = actix_web::web::Data::new(app_state);
let server = actix_web::HttpServer::new(move || {
actix_web::App::new()
.app_data(state.clone())
.route("/health_check", actix_web::web::get().to(health_check))
})
.listen(listener)?
.run();
Ok(server)
}For Axum, prefer the same boundary but use Tokio's async listener type:
rust
pub fn router(app_state: AppState) -> axum::Router {
axum::Router::new()
.route("/health_check", axum::routing::get(health_check))
.with_state(app_state)
}
pub async fn spawn_axum_app() -> TestApp {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = axum::serve(listener, router(test_state().await));
let server_handle = tokio::spawn(async move { server.await });
TestApp {
address: format!("http://127.0.0.1:{port}"),
http_client: reqwest::Client::new(),
server_handle,
}
}优先使用接收基础设施对象的启动函数,而不是在 handler 模块内部创建它。
Actix 可以监听同步的 :
std::net::TcpListenerrust
pub fn run(
listener: std::net::TcpListener,
app_state: AppState,
) -> Result<actix_web::dev::Server, std::io::Error> {
let state = actix_web::web::Data::new(app_state);
let server = actix_web::HttpServer::new(move || {
actix_web::App::new()
.app_data(state.clone())
.route("/health_check", actix_web::web::get().to(health_check))
})
.listen(listener)?
.run();
Ok(server)
}对于 Axum,优先采用相同的边界,但使用 Tokio 的异步 listener 类型:
rust
pub fn router(app_state: AppState) -> axum::Router {
axum::Router::new()
.route("/health_check", axum::routing::get(health_check))
.with_state(app_state)
}
pub async fn spawn_axum_app() -> TestApp {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = axum::serve(listener, router(test_state().await));
let server_handle = tokio::spawn(async move { server.await });
TestApp {
address: format!("http://127.0.0.1:{port}"),
http_client: reqwest::Client::new(),
server_handle,
}
}Test Harness Pattern
Test Harness 模式
Use a helper object instead of repeating setup in every test.
rust
pub struct TestApp {
pub address: String,
pub http_client: reqwest::Client,
pub server_handle: tokio::task::JoinHandle<std::io::Result<()>>,
}
pub async fn spawn_app() -> TestApp {
let listener = std::net::TcpListener::bind("127.0.0.1:0")
.expect("failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = my_app::startup::run(listener, test_state().await)
.expect("failed to start test server");
let server_handle = tokio::spawn(server);
TestApp {
address: format!("http://127.0.0.1:{port}"),
http_client: reqwest::Client::new(),
server_handle,
}
}Add small helper methods when a multi-step user journey appears in more than
one test. Keep the method names behavior-oriented, for example
, , , or .
post_subscriptionlogincreate_newsletterconfirm_subscriptionDo not discard the returned by . Keep it in the test
fixture so tests can detect an unexpectedly finished server task and abort it
during teardown instead of hiding server-side panics behind later
connection-refused errors.
JoinHandletokio::spawn使用辅助对象,避免在每个测试中重复设置环境。
rust
pub struct TestApp {
pub address: String,
pub http_client: reqwest::Client,
pub server_handle: tokio::task::JoinHandle<std::io::Result<()>>,
}
pub async fn spawn_app() -> TestApp {
let listener = std::net::TcpListener::bind("127.0.0.1:0")
.expect("failed to bind random port");
let port = listener.local_addr().unwrap().port();
let server = my_app::startup::run(listener, test_state().await)
.expect("failed to start test server");
let server_handle = tokio::spawn(server);
TestApp {
address: format!("http://127.0.0.1:{port}"),
http_client: reqwest::Client::new(),
server_handle,
}
}当包含多个步骤的用户流程出现在多个测试中时,添加小型辅助方法。
方法名应体现具体行为,例如 、、
或 。
post_subscriptionlogincreate_newsletterconfirm_subscription不要丢弃 返回的 。将其保留在 test fixture 中,
使测试能够检测到意外结束的 server task,并在 teardown 阶段中止它,
而不是让 server 端 panic 被后续的 connection refused 错误掩盖。
tokio::spawnJoinHandleAssertions
断言
- Assert status codes and response headers first.
- Assert persisted side effects through public APIs when possible; query the database directly only when the public API has no observation point yet.
- Assert negative cases as first-class behavior: missing fields, malformed payloads, duplicate submissions, unauthorized users, upstream failures, and timeouts.
- Avoid snapshotting noisy response bodies unless the API contract actually includes those exact bytes.
- 首先断言状态码和响应头。
- 尽可能通过公共 API 断言已持久化的副作用;仅当公共 API 尚无可观察点时,才直接查询数据库。
- 将负面场景作为一等行为进行断言:缺少字段、格式错误的载荷、 重复提交、未授权用户、上游故障和超时。
- 除非 API 契约确实包含那些精确字节,否则避免对噪声较多的 响应正文创建 snapshot。
State And Dependency Isolation
状态与依赖隔离
Read when tests touch a database.
Read when tests call third-party HTTP APIs.
references/database-test-isolation.mdreferences/external-http-mocks.mdDefault preferences:
- Use real Postgres for Postgres-backed behavior instead of SQLite or in-memory substitutes.
- Use one logical database, schema, or unique namespace per test when tests can write shared state.
- Run migrations in setup before the app starts.
- Use or an equivalent local mock server for external HTTP APIs.
wiremock - Configure timeouts aggressively in tests so failures do not hang.
当测试涉及数据库时,阅读 。
当测试调用第三方 HTTP API 时,阅读 。
references/database-test-isolation.mdreferences/external-http-mocks.md默认偏好:
- 对于依赖 Postgres 的行为,使用真实 Postgres,而不是 SQLite 或内存替代品。
- 当测试可能写入共享状态时,为每个测试使用独立的逻辑数据库、 schema 或唯一命名空间。
- 在应用启动前的 setup 阶段运行 migrations。
- 对外部 HTTP API 使用 或等效的本地 mock 服务器。
wiremock - 在测试中积极配置 timeouts,避免失败时长时间挂起。
Verification
验证
Run the bundled preflight script from the Rust project root when the standard
cargo workflow applies:
bash
path/to/rust-api-test-harness/scripts/check-rust-service.shBy default, the script runs:
bash
cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-featuresSet to skip only the clippy step. The
script still runs formatting and tests. Use this escape hatch when the project
configures linting separately in CI or when is
known to be inappropriate for the local preflight.
RUST_API_TEST_HARNESS_SKIP_CLIPPY=1--all-targets --all-featuresIf the project does not use all features in CI, mirror the repository's existing
CI commands instead and explain the deviation.
当标准 cargo 工作流适用时,从 Rust 项目根目录运行随附的 preflight 脚本:
bash
path/to/rust-api-test-harness/scripts/check-rust-service.sh默认情况下,脚本会运行:
bash
cargo fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-features设置 可仅跳过 clippy 步骤。
脚本仍会运行格式检查和测试。当项目在 CI 中单独配置 lint,
或者已知 不适合本地 preflight 时,
可以使用此应急出口。
RUST_API_TEST_HARNESS_SKIP_CLIPPY=1--all-targets --all-features如果项目的 CI 未使用全部 features,请改为遵循仓库现有的 CI 命令,
并说明其中的差异。
Reference Files
参考文件
- : patterns for Postgres-backed tests, migrations, per-test databases, and cleanup tradeoffs.
references/database-test-isolation.md - : patterns for testing outbound HTTP clients and API workflows with local mocks.
references/external-http-mocks.md
- :Postgres 支持的测试模式、migrations、 每个测试使用独立数据库以及清理策略的权衡。
references/database-test-isolation.md - :使用本地 mock 测试出站 HTTP 客户端 和 API 工作流的模式。
references/external-http-mocks.md