Rust模块测试#[test]指南

在 Rust 中,测试主要通过 cargo test 命令执行。根据你的测试代码所在位置(单元测试集成测试文档测试),操作方式略有不同:

1. 常用测试指令

目标命令
运行所有测试 cargo test
运行特定函数 cargo test 函数名(支持模糊匹配)
精确匹配函数 cargo test 函数名 -- --exact
查看打印输出 cargo test -- --nocapture(默认隐藏 println!
运行忽略的测试 cargo test -- --ignored(针对标记了 #[ignore] 的测试)

2. 测试分类与实践

A. 单元测试 (Unit Tests)
通常写在源文件末尾,放在 cfg(test) 模块中。
// src/lib.rs 或 src/main.rs
pub fn add(a: i32, b: i32) -> i32 { a + b }

#[cfg(test)]
mod tests {
    use super::*; // 引入外部代码

    #[test]
    fn it_works() {
        assert_eq!(add(2, 2), 4);
    }
}
运行命令:cargo test tests::it_works
B. 集成测试 (Integration Tests)
存放在项目根目录下的 tests/ 文件夹中,只能测试 pub 接口。
  • 文件路径:tests/my_integration_test.rs
  • 运行命令:cargo test --test my_integration_test
C. 文档测试 (Doc Tests)
写在函数上方的注释中,既是示例又是测试。
/// ```
/// assert_eq!(my_crate::add(1, 1), 2);
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }
运行命令:cargo test --doc

3. 高级过滤

如果你的项目是 Workspace (工作空间),需要指定包名:
cargo test -p <crate_name> --lib <path::to::module>
提示:在开发过程宏 (Procedural Macros) 时,由于其特殊的编译机制,通常推荐使用 trybuild 或 ui_test 库进行编译期错误和展开结果的测试。

参考资料:

1.rust开源库test_case参数化测试

2.

posted @ 2026-01-30 17:10  PKICA  阅读(3)  评论(0)    收藏  举报