GoogleTest

The GoogleTest crate allows for flexible test assertions using matchers:

  1. use googletest::prelude::*;
  2. #[googletest::test]
  3. fn test_elements_are() {
  4. let value = vec!["foo", "bar", "baz"];
  5. expect_that!(value, elements_are!(eq(&"foo"), lt(&"xyz"), starts_with("b")));
  6. }

If we change the last element to "!", the test fails with a structured error message pin-pointing the error:

  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 is not part of the Rust Playground, so you need to run this example in a local environment. Use cargo add googletest to quickly add it to an existing Cargo project.

  • The use googletest::prelude::*; line imports a number of commonly used macros and types.

  • This just scratches the surface, there are many builtin matchers. Consider going through the first chapter of “Advanced testing for Rust applications”, a self-guided Rust course: it provides a guided introduction to the library, with exercises to help you get comfortable with googletest macros, its matchers and its overall philosophy.

  • 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. }

shows a color-coded diff (colors not shown here):

  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