用 cargo test 跑通单元与集成测试:过滤名、-- 传参怎么确认
准备工作
已安装 Rustup/Cargo,
cargo --version可用。步骤依据 The Cargo Book 的
cargo-test(1)页面,核实日期 2026-10-24。[1]任意有
#[test]的包,或cargo new --lib demo && cd demo。
操作步骤
1、在包根目录执行默认测试
做什么:cargo test
为什么:Cargo 会编译并执行单元测试、集成测试与文档测试。手册 SYNOPSIS 写明 cargo test [options] [testname] [-- test-options]。[1]
怎么确认:输出出现 running N tests 且最终 test result: ok;失败则有失败用例名与断言信息。
2、用测试名过滤
做什么:cargo test partial_name
为什么:手册说明 test filtering 参数会传给测试二进制,只跑名称匹配的用例,缩短反馈周期。[1]
怎么确认:日志里只跑匹配用例;改成不存在的名字时应显示 0 tested 或相应过滤结果(以你 Cargo 版本输出为准)。
3、向测试二进制传额外参数
做什么:cargo test -- --nocapture 或 cargo test -- --test-threads=1
为什么:两个短横线之后的参数交给 libtest,而不是 Cargo 自己。手册明确 -- 后为 test-options。[1]
怎么确认:--nocapture 时能直接看到 println! 输出;--test-threads=1 时用例串行(日志顺序更稳定)。
4、只测某一目标(示例)
做什么:cargo test --lib 或 cargo test --test integ_name(若有 tests/ 集成测试文件)
为什么:大仓库里分开跑库测试与集成测试更快定位。[1]
怎么确认:命令只编译/执行对应目标;cargo test --help 能看到这些开关说明。
注意事项
文档测试失败常因示例代码未同步,别只盯单元测试。
CI 上固定
--test-threads有助于复现竞态,但会变慢。
来源
[1] The Cargo Book · cargo-test · https://doc.rust-lang.org/cargo/commands/cargo-test.html · 核实于 2026-10-24
#Rust #cargo #测试 #教程 #cargo-test

成为第一条评论!
Nobody's responded to this post yet. Add your thoughts and get the conversation going.