For AI agents: the complete documentation index is available at https://a3s-lab.github.io/Boot/llms.txt, the full documentation bundle is available at https://a3s-lab.github.io/Boot/llms-full.txt, and this page is available as Markdown at https://a3s-lab.github.io/Boot/reference/testing.md.
  • 简体中文
  • v0.2.0
  • 测试

    TestingModule 在进程内编译真实 Boot 应用图,同时允许在 Controller 构建前替换 Provider、Module 和管线组件。测试调用不需要打开 socket。

    最小 HTTP 测试

    #[tokio::test]
    async fn greeting_uses_test_provider() {
        let testing = TestingModule::builder()
            .import(GreetingModule)
            .override_provider(ProviderDefinition::singleton(GreetingService {
                message: "fake",
            }))
            .compile()?;
    
        let response = testing
            .call(BootRequest::new(HttpMethod::Get, "/greetings"))
            .await?;
    
        assert_eq!(response.status(), 200);
        assert_eq!(response.body_text()?, "fake");
        Ok::<(), BootError>(())
    }

    Override 在导入图解析和 Controller factory 运行前应用,因此 injected Controller 会得到 replacement,而不是先构造 production 实例再修改。

    Builder 能力

    方法用途
    import, import_arc导入 production Module
    provider为测试动态 Module 添加 Provider
    controller, route直接加入 HTTP surface
    gateway加入 WebSocket Gateway
    message_pattern加入 transport pattern
    override_provider按 token 替换 ProviderDefinition
    override_module, override_module_arc按稳定 module name 替换直接或嵌套 Module
    compile构建同步 Provider 图
    compile_async等待 async Provider factory 后构建

    TestingModule::get、get_named 与 optional 变体解析 Provider。app() 提供完整 in-process application,into_app() 转移所有权。

    Pipeline override

    Testing builder 可以按具体组件类型替换:

    • HTTP Guard, Interceptor, Pipe, ExceptionFilter
    • WebSocket WebSocketGuard, WebSocketInterceptor, WebSocketPipe, WebSocketExceptionFilter
    • Transport TransportGuard, TransportInterceptor, TransportPipe, TransportExceptionFilter

    Replacement 会应用到已编译的 route、Gateway、message pattern 与 global filter。用它隔离外部认证或观测组件,同时继续执行真实业务 handler。

    不要把所有测试都改成 allow-all Guard。至少保留一组 integration test 覆盖真实认证、授权和错误映射。

    HTTP 调用

    TestingModule::call 与 BootApplication::call 返回 framework-level error,适合断言成功路径和明确错误。BootApplication::handle 把错误转换成最终默认或 Filter 响应,适合断言 HTTP wire contract。

    构造 BootRequest 时显式设置 method、path、query、header、cookie 与 body。测试 path specificity、global prefix、host、API version 与 content negotiation 时,要把影响匹配的输入全部写进 request。

    WebSocket 测试

    从 testing.app().gateway_for(path) 得到 Gateway,调用 connect(BootRequest) 创建 in-process connection,再用 dispatch(WebSocketMessage) 验证 reply、room、broadcast、lifecycle 与 Filter。

    分别覆盖 unknown event、bad payload、Guard deny、Pipe transform、Interceptor recovery、disconnect cleanup 和多 connection room 行为。实际 Axum upgrade 仍需要 socket-level integration test。

    Transport 测试

    app.dispatch_message(TransportMessage) 可以直接验证注册 pattern。InProcessTransport 适合 client request-response 与 event flow。网络实现还需要对应 broker 或 ephemeral service 测试连接、serialization、timeout 与 restart。

    不要用 in-process 结果推断 Redis、Kafka、RabbitMQ 或 MQTT 的 durability 和 ordering。

    Scope 与生命周期

    • 同一 request 或 dispatch 中的 request-scoped Provider 应复用。
    • 不同 ContextId 不应泄漏 request state。
    • Transient Provider 应按 inquirer 语义构造。
    • bootstrap 与 shutdown 测试应断言 hook 顺序和 signal label。
    • Async Provider 测试使用 compile_async,不能在 async context 内阻塞等待。

    外部资源测试

    测试必须清理临时文件、listener、connection 与 task。PostgreSQL queue integration test 使用独立 schema 或唯一 queue name,并在结束时清理。缺少外部服务时应明确 skip 条件,不能把连接失败误报成通过。

    仓库内推荐检查:

    cargo fmt --all -- --check
    cargo test
    cargo test --all-features
    cargo clippy --all-targets --all-features -- -D warnings
    RUSTDOCFLAGS="-D warnings" cargo doc --all-features --no-deps

    从 a3s-boot crate 目录运行这些命令。