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
-
GoogleTest は Rust Playground の一部ではないため、この例はローカル環境で実行 する必要があります。既存の Cargo プロジェクトにすばやく追加するには
cargo add googletestを使用してください。 -
use googletest::prelude::*;行は、 よく使われるマクロと型 をいくつかインポートします。 -
これはほんの入り口にすぎず、組み込みのマッチャーは数多くあります。自習形式の Rust コース “Rust アプリケーションのための高度なテスト” の第 1 章を読んでみるとよいでしょう。この章ではライブラリのガイド付き入門が 提供されており、
googletestのマクロ、そのマッチャー、そして全体的な設計 思想に慣れるのに役立つ演習も含まれています。 -
特に便利な機能として、複数行文字列の不一致が差分として表示されます。
// 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.")
);
}
色分けされた差分が表示されます(ここでは色は表示していません)。
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
- このクレートは GoogleTest for C++ の Rust 移植版です。