You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust中通过属性禁用单元测试?如何仅运行指定测试?

方案1:禁用指定单元测试

给不需要运行的测试函数添加#[ignore]属性即可,默认执行测试时会跳过标记了该属性的用例:

#[cfg(test)]
mod tests_cases {
    #[test]
    #[ignore] // 添加该属性即可禁用对应测试
    fn test_1() {
        let a = 1;
        let b = 2;
        println!("{},{}", a, b);
        assert_ne!(a, b);
    }

    #[test]
    fn test_2() {
        let c = 1;
        let d = 1;
        println!("currently working on this: {},{}", c, d);
        assert_eq!(c, d);
    }
}

如果后续需要运行所有被忽略的测试,执行cargo test -- --ignored即可。

方案2:仅运行指定单元测试

不需要修改代码,直接在cargo test后传入测试名作为过滤参数即可,默认会运行所有名称包含该字符串的测试用例:

  • 仅运行test2同时关闭输出捕获的命令为:
    cargo test test2 -- --nocapture
  • 如果需要精确匹配测试名,避免误匹配到其他名称包含test2的测试,可以加--exact参数:
    cargo test test2 --exact -- --nocapture

内容的提问来源于stack exchange,提问作者chriamue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:06:01