#test-cases #case #unit-testing #unit #test-macro #proc-macro

dev test-case-macros

提供 #[test_case(...)] 过程宏属性,用于轻松生成参数化测试用例。

9 个稳定版本

3.3.1 2023 年 11 月 17 日
3.2.1 2023 年 9 月 17 日
3.1.0 2023 年 4 月 2 日
3.0.0 2023 年 2 月 13 日
2.1.0 2022 年 5 月 18 日

851测试

Download history 85466/week @ 2024-03-14 80106/week @ 2024-03-21 95619/week @ 2024-03-28 89277/week @ 2024-04-04 88638/week @ 2024-04-11 92201/week @ 2024-04-18 92219/week @ 2024-04-25 93833/week @ 2024-05-02 87789/week @ 2024-05-09 89020/week @ 2024-05-16 88234/week @ 2024-05-23 92816/week @ 2024-05-30 96243/week @ 2024-06-06 97077/week @ 2024-06-13 93643/week @ 2024-06-20 77110/week @ 2024-06-27

382,459 每月下载量
563 个 crate 中使用(通过 test-case

MIT 许可证

75KB
1.5K SLoC

Crates.io Crates.io Docs.rs MIT License Build Status Maintenance

测试用例

概述

test_case crate 提供过程宏属性,用于生成参数化测试实例。

入门

需要将 crate 添加到 Cargo.toml 作为依赖项

[dev-dependencies]
test-case = "*"

并将它导入到调用它的代码块的作用域中(由于属性名称与 Rust 内置的 custom_test_frameworks 冲突),如下所示

use test_case::test_case;

示例用法

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

    #[test_case(-2, -4 ; "when both operands are negative")]
    #[test_case(2,  4  ; "when both operands are positive")]
    #[test_case(4,  2  ; "when operands are swapped")]
    fn multiplication_tests(x: i8, y: i8) {
        let actual = (x * y).abs();

        assert_eq!(8, actual)
    }
}

此示例的 cargo test 输出

$ cargo test

running 4 tests
test tests::multiplication_tests::when_both_operands_are_negative ... ok
test tests::multiplication_tests::when_both_operands_are_positive ... ok
test tests::multiplication_tests::when_operands_are_swapped ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

测试矩阵

#[test_matrix(...)] 宏允许从每个测试函数参数的可能值的笛卡尔积中生成多个测试用例。 test_matrix 宏的参数数量必须与测试函数的参数数量相同。每个宏参数可以是

1. A list in array (`[x, y, ...]`) or tuple (`(x, y, ...)`) syntax. The values can be any
   valid [expression](https://doc.rust-lang.org/reference/expressions.html).
2. A closed numeric range expression (e.g. `0..100` or `1..=99`), which will generate
   argument values for all integers in the range.
3. A single expression, which can be used to keep one argument constant while varying the
   other test function arguments using a list or range.

示例用法

#[cfg(test)]
mod tests {
    use test_case::test_matrix;

    #[test_matrix(
        [-2, 2],
        [-4, 4]
    )]
    fn multiplication_tests(x: i8, y: i8) {
        let actual = (x * y).abs();

        assert_eq!(8, actual)
    }
}

MSRV 政策

从版本 3.0 开始,test-case 仅支持最新的稳定 Rust。这些更改可能会在夜间发生,因此如果您的堆栈落后于当前的稳定版本,最好考虑在您的 Cargo.toml 中使用 = 锁定 test-case 版本。

文档

最新文档可在我们的 wiki 上找到。

许可证

本软件采用MIT许可协议(LICENSE-MIThttps://opensource.org/licenses/MIT

贡献

项目路线图可在链接处查看。欢迎所有贡献。

推荐工具

  • cargo readme - 生成基于模板和lib.rs注释的README.md
  • cargo insta - 查看测试快照
  • cargo edit - 添加/删除依赖项
  • cargo fmt - 格式化代码
  • cargo clippy - 提供所有见解和建议
  • cargo fix - 修复警告

依赖项

~255–700KB
~17K SLoC