Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

GoogleTest

Крейт GoogleTest позволяет гибко писать проверки в тестах с помощью матчеров:

// Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0

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")));
}

Если изменить последний элемент на "!", тест упадёт со структурированным сообщением об ошибке, которое точно указывает на проблему:

---- 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
This slide should take about 5 minutes.
  • GoogleTest не входит в Rust Playground, поэтому этот пример нужно запускать в локальной среде. Чтобы быстро добавить его в существующий проект Cargo, используйте cargo add googletest.

  • Строка use googletest::prelude::*; импортирует ряд часто используемых макросов и типов.

  • Это лишь верхушка айсберга: встроенных матчеров много. Стоит пройти первую главу “Advanced testing for Rust applications”, самостоятельного курса по Rust: в ней даётся пошаговое введение в библиотеку, с упражнениями, которые помогут освоиться с макросами googletest, её матчерами и общей философией.

  • Особенно удобно, что различия в многострочных строках показываются в виде diff:

// Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0

#[test]
fn test_multiline_string_diff() {
    let haiku = "Memory safety found,\n\
                 Rust's strong typing guides the way,\n\
                 Secure code you'll write.";
    assert_that!(
        haiku,
        eq("Memory safety found,\n\
            Rust's silly humor guides the way,\n\
            Secure code you'll write.")
    );
}

показывает цветной diff (цвета здесь не показаны):

    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