集成测试

单元测试一次仅能单独测试一个模块,这种测试是小规模的,并且能测试私有 代码;集成测试是 crate 外部的测试,并且仅使用 crate 的公共接口,就像其他使用 该 crate 的程序那样。集成测试的目的是检验你的库的各部分是否能够正确地协同工作。

cargo 在与 src 同级别的 tests 目录寻找集成测试。

文件 src/lib.rs

  1. // 在一个叫做 'adder' 的 crate 中定义此函数。
  2. pub fn add(a: i32, b: i32) -> i32 {
  3. a + b
  4. }

包含测试的文件:tests/integration_test.rs

  1. #[test]
  2. fn test_add() {
  3. assert_eq!(adder::add(3, 2), 5);
  4. }

使用 cargo test 命令:

  1. $ cargo test
  2. running 0 tests
  3. test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
  4. Running target/debug/deps/integration_test-bcd60824f5fbfe19
  5. running 1 test
  6. test test_add ... ok
  7. test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
  8. Doc-tests adder
  9. running 0 tests
  10. test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

tests 目录中的每一个 Rust 源文件都被编译成一个单独的 crate。在集成测试中要想 共享代码,一种方式是创建具有公用函数的模块,然后在测试中导入并使用它。

文件 tests/common.rs:

  1. pub fn setup() {
  2. // 一些配置代码,比如创建文件/目录,开启服务器等等。
  3. }

包含测试的文件:tests/integration_test.rs

  1. // 导入共用模块。
  2. mod common;
  3. #[test]
  4. fn test_add() {
  5. // 使用共用模块。
  6. common::setup();
  7. assert_eq!(adder::add(3, 2), 5);
  8. }

带有共用代码的模块遵循和普通的模块一样的规则,所以完全可以把公共模块 写在 tests/common/mod.rs 文件中。