Debian系统中Rust如何测试

在Debian系统中测试Rust项目,步骤如下:

  1. 安装Rust:通过命令安装并配置环境变量

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh  
    source $HOME/.cargo/env  
    
  2. 创建项目:用cargo new生成新项目

    cargo new my_project  
    cd my_project  
    
  3. 编写测试代码:在src/lib.rssrc/main.rs中添加#[cfg(test)]模块及#[test]函数

    #[cfg(test)]  
    mod tests {  
        use super::*;  
        #[test]  
        fn test_example() {  
            assert_eq!(2 + 2, 4);  
        }  
    }  
    
  4. 运行测试:使用cargo test命令执行所有测试

    cargo test  
    
  5. 常用选项

    • 查看详细输出:cargo test -- --nocapture
    • 运行特定测试:cargo test 测试函数名
    • 并行控制:cargo test -- --test-threads=1
  6. 持续集成(可选):可配置GitHub Actions等工具自动运行cargo test