GoogleTest

The GoogleTest crate allows for flexible test assertions using matchers:

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

Si cambiamos el último elemento a "!", la prueba dará error y aparecerá un mensaje de error estructurado que señala cuál es el fallo:

---- test_elements_are stdout ---- Value of: value Expected: has elements: 0. is equal to "foo" 1. is less than "xyz" 2. starts with prefix "!" Actual: ["foo", "bar", "baz"], where element #2 is "baz", which does not start with "!" at src/testing/googletest.rs:6:5 Error: See failure output above

Speaker Notes

This slide should take about 5 minutes.
  • GoogleTest no forma parte de Rust Playground, por lo que debes llevar a cabo este ejemplo en un entorno local. Usa cargo add googletest para añadirlo rápidamente a un proyecto de Cargo que ya tengas.

  • La línea use googletest::prelude::*; importa una serie de macros y tipos habituales.

  • 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:

#[test] fn test_multiline_string_diff() { let haiku = "Se ha encontrado la seguridad de la memoria,\n\ la potente escritura de Rust guía el camino,\n\ protege el código que vayas a escribir."; assert_that!( haiku, eq("Se ha encontrado seguridad en la memoria,\n\ el divertido sentido del humor de Rust guía el camino,\n\ protege el código que vayas a escribir.") ); }

muestra un diff con colores (colores que no se muestran aquí):

Value of: haiku Expected: is equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write." Actual: "Memory safety found,\nRust's strong typing guides the way,\nSecure code you'll write.", which isn't equal to "Memory safety found,\nRust's silly humor guides the way,\nSecure code you'll write." Difference(-actual / +expected): Memory safety found, -Rust's strong typing guides the way, +Rust's silly humor guides the way, Secure code you'll write. at src/testing/googletest.rs:17:5