在Rust项目中,一般测试用例函数 #[(test)] 都写在哪里? 如果要测试 main.rs 文件中的函数该怎么做?

eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

在 Rust 项目中,测试用例通常放在以下两个位置:

1. 与源代码同文件中的模块

  • 测试用例函数一般写在与实现代码同一个文件中,放在一个名为 tests 的模块里,使用 #[cfg(test)] 注解。
  • 这种方式适用于对模块内的函数或逻辑进行单元测试。

示例如下:

// main.rs 文件中的函数
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

// 测试模块
#[cfg(test)]
mod tests {
    use super::*; // 引入外部作用域的实现代码

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }
}

2. 独立的测试文件

  • 如果项目是一个库或较大规模的项目,可以将测试用例写在 tests 目录下的独立文件中。
  • 这种方式通常用于集成测试,而不是单元测试。测试文件通过 use 语句引入需要测试的模块。

示例如下:

project/
├── src/
│   ├── lib.rs   // 实现代码
│   └── main.rs  // 主程序入口
└── tests/
    └── integration_test.rs  // 集成测试文件

tests/integration_test.rs 中:

use your_crate_name::add; // 引入库函数

#[test]
fn test_add_integration() {
    assert_eq!(add(2, 3), 5);
}

如果要测试 main.rs 文件中的函数:

  1. 将函数公开

    • 如果 main.rs 中的函数需要测试,可以将它们标记为 pub,以便可以从其他模块访问。
  2. 直接在 main.rs 中写测试用例

    • 如第一个示例,直接在 main.rs#[cfg(test)] 模块中编写测试用例。
  3. 提取逻辑到 lib.rs

    • 推荐的方式是将 main.rs 中的逻辑提取到一个库文件 lib.rs 中。
    • 这样可以在 lib.rs 中实现所有功能逻辑,main.rs 仅作为入口调用这些函数。
    • 测试用例可以直接写在 lib.rs 文件中,或者在 tests 目录中进行集成测试。

示例:

src/
├── lib.rs   // 提取逻辑到此文件
├── main.rs  // 调用 lib.rs 中的逻辑

lib.rs

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }
}

main.rs

use your_crate_name::add;

fn main() {
    let result = add(2, 3);
    println!("2 + 3 = {}", result);
}

posted on 2025-01-23 16:39  及途又八  阅读(106)  评论(0)    收藏  举报

导航