Rust项目文件结构配置:如何让测试访问目标函数并简化测试配置?
解决Rust测试中
rwarden未声明及函数测试可见性问题 1. 确保目标函数对外可见
首先把calculate_sha256_hash标记为pub,让测试代码能访问它:
// src/lib.rs(如果是library crate)或对应模块文件 pub fn calculate_sha256_hash(input: &str) -> String { // 你的哈希计算实现 }
2. 正确编写测试,无需修改Cargo.toml
根据测试类型选择对应写法,Cargo会自动识别测试,无需手动修改配置:
单元测试(和业务代码同文件)
在包含calculate_sha256_hash的文件末尾,用#[cfg(test)]包裹测试模块,通过super::或crate::引用目标函数:
#[cfg(test)] mod tests { // 引用当前模块的函数 use super::calculate_sha256_hash; // 如果函数在其他子模块,比如src/hash.rs,用 use crate::hash::calculate_sha256_hash; #[test] fn test_sha256_hash() { let test_input = "hello world"; let expected_hash = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; assert_eq!(calculate_sha256_hash(test_input), expected_hash); } }
集成测试(独立文件,无需改Cargo.toml)
在项目根目录创建tests/文件夹,每个测试文件直接引用你的crate名称即可。Cargo会自动扫描这个目录下的所有测试文件,新增测试只需添加新文件:
// tests/hash_integration_test.rs use rwarden::calculate_sha256_hash; #[test] fn test_integration_hash() { let result = calculate_sha256_hash("test"); assert_eq!(result, "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"); }
3. 处理Binary Crate的特殊情况
如果你的项目是仅包含main.rs的binary crate,测试无法直接引用它。解决方法是把核心逻辑(比如calculate_sha256_hash)移到src/lib.rs中,将项目转为library + binary的结构:
- 创建
src/lib.rs,放入pub fn calculate_sha256_hash - 在
src/main.rs中通过use rwarden::calculate_sha256_hash;调用该函数 - 之后测试就能正常引用
rwardencrate了
内容的提问来源于stack exchange,提问作者Mher Didaryan
相关产品推荐
相关产品推荐

