测试属性
以下属性用于指定执行测试的函数。在“测试“模式下编译 crate 会启用构建测试函数以及执行测试的测试工具。启用测试模式还会启用 test 条件编译选项。
test 属性
test 属性 将函数标记为要作为测试执行。
Example
#![allow(unused)] fn main() { pub fn add(left: u64, right: u64) -> u64 { left + right } #[test] fn it_works() { let result = add(2, 2); assert_eq!(result, 4); } }
test 属性使用 MetaWord 语法。
test 属性只能应用于自由函数,这些函数必须是单态的、不带参数,并且返回类型实现 Termination trait。
Note
实现
Terminationtrait 的一些类型包括:
()Result<T, E> where T: Termination, E: Debug
只有函数上的第一次使用 test 才有效果。
Note
rustc会对第一次之后的任何使用发出 lint 警告。这可能在未来成为错误。
test 属性从标准库 prelude 导出为 std::prelude::v1::test。
这些函数仅在测试模式下编译。
Note
通过将
--test参数传递给rustc或使用cargo test来启用测试模式。
测试工具调用返回值的 report 方法,并根据结果 ExitCode 是否表示成功终止来将测试分类为通过或失败。
特别是:
- 返回
()的测试只要终止且不 panic 就通过。 - 返回
Result<(), E>的测试只要返回Ok(())就通过。 - 返回
ExitCode::SUCCESS的测试通过,返回ExitCode::FAILURE的测试失败。 - 不终止的测试既不通过也不失败。
Example
#![allow(unused)] fn main() { use std::io; fn setup_the_thing() -> io::Result<i32> { Ok(1) } fn do_the_thing(s: &i32) -> io::Result<()> { Ok(()) } #[test] fn test_the_thing() -> io::Result<()> { let state = setup_the_thing()?; // expected to succeed do_the_thing(&state)?; // expected to succeed Ok(()) } }
ignore 属性
ignore 属性 可与 test 属性一起使用,告诉测试工具不要将该函数作为测试执行。
Example
#![allow(unused)] fn main() { #[test] #[ignore] fn check_thing() { // … } }
Note
rustc测试工具支持--include-ignored标志以强制运行被忽略的测试。
ignore 属性使用 MetaWord 和 MetaNameValueStr 语法。
ignore 属性的 MetaNameValueStr 形式提供了一种指定测试被忽略原因的方式。
Example
#![allow(unused)] fn main() { #[test] #[ignore = "not yet implemented"] fn mytest() { // … } }
ignore 属性只能应用于带有 test 属性注释的函数。
Note
rustc会忽略在其他位置的使用,但会发出 lint 警告。这可能在未来成为错误。
只有函数上的第一次使用 ignore 才有效果。
Note
rustc会对第一次之后的任何使用发出 lint 警告。这可能在未来成为错误。
被忽略的测试在测试模式下仍然被编译,但不会被执行。
should_panic 属性
should_panic 属性 仅在应用该属性的测试函数 panic 时才使测试通过。
Example
#![allow(unused)] fn main() { #[test] #[should_panic(expected = "values don't match")] fn mytest() { assert_eq!(1, 2, "values don't match"); } }
should_panic 属性具有以下形式:
-
Example
#![allow(unused)] fn main() { #[test] #[should_panic] fn mytest() { panic!("error: some message, and more"); } } -
MetaNameValueStr — 给定的字符串必须出现在 panic 消息中,测试才能通过。
Example
#![allow(unused)] fn main() { #[test] #[should_panic = "some message"] fn mytest() { panic!("error: some message, and more"); } } -
MetaListNameValueStr — 与 MetaNameValueStr 语法一样,给定的字符串必须出现在 panic 消息中。
Example
#![allow(unused)] fn main() { #[test] #[should_panic(expected = "some message")] fn mytest() { panic!("error: some message, and more"); } }
should_panic 属性只能应用于带有 test 属性注释的函数。
Note
rustc会忽略在其他位置的使用,但会发出 lint 警告。这可能在未来成为错误。
只有函数上的第一次使用 should_panic 才有效果。
Note
rustc会对第一次之后的任何使用发出带有未来兼容性警告的 lint 警告。这可能在未来成为错误。
当使用 MetaNameValueStr 形式或带有 expected 键的 MetaListNameValueStr 形式时,给定的字符串必须出现在 panic 消息中的某处,测试才能通过。
测试函数的返回类型必须是 ()。