GoogleTest
The GoogleTest crate allows for flexible test assertions using matchers:
1. use googletest::prelude::*;
3. #[googletest::test]
4. fn test_elements_are() {
5. let value = vec!["foo", "bar", "baz"];
6. expect_that!(value, elements_are!(eq("foo"), lt("xyz"), starts_with("b")));
7. }
如果我们将最后一个元素更改为 "!",测试将失败,并会提供详细的错误消息来指出错误的位置:
1. ---- test_elements_are stdout ----
2. Value of: value
3. Expected: has elements:
4. 0. is equal to "foo"
5. 1. is less than "xyz"
6. 2. starts with prefix "!"
7. Actual: ["foo", "bar", "baz"],
8. where element #2 is "baz", which does not start with "!"
9. at src/testing/googletest.rs:6:5
10. Error: See failure output above
This slide should take about 5 minutes.
- GoogleTest 不是 Rust Playground 的一部分,因此您需要在本地环境中运行此示例。使用
cargo add googletest快速将其添加到现有 Cargo 项目中。 use googletest::prelude::*;行会导入一些 常用的宏和类型。- 这只是冰山一角,还有很多内置匹配器。
- A particularly nice feature is that mismatches in multi-line strings are shown as a diff:
1. #[test]
2. fn test_multiline_string_diff() {
3. let haiku = "Memory safety found,\n\
4. Rust's strong typing guides the way,\n\
5. Secure code you'll write.";
6. assert_that!(
7. haiku,
8. eq("Memory safety found,\n\
9. Rust's silly humor guides the way,\n\
10. Secure code you'll write.")
11. );
12. }
显示用颜色标识的差异(此处未显示颜色):
1. Value of: haiku
2. Expected: is equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write."
3. Actual: "Memory safety found,\nRust's strong typing guides the way,\nSecure code you'll write.",
4. which isn't equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write."
5. Difference(-actual / +expected):
6. Memory safety found,
7. -Rust's strong typing guides the way,
8. +Rust's silly humor guides the way,
9. Secure code you'll write.
10. at src/testing/googletest.rs:17:5
- crate 是 适用于 C++ 的 GoogleTest 的 Rust 移植版。
