cargo test でのテスト対象の指定方法について。

基礎知識

コマンドの構文

cargo test [options] [testname] [-- test-options]

コマンドは二段構成になっている。

options までは cargo が自分で処理する。

testname 以降はテスト実行機能 libtest に渡される。

cargo コマンドのオプション

テスト対象をビルド成果物の単位で絞り込む (公式資料)。

以下は代表的なオプションの抜粋。

--workspace
ワークスペース全体
--package name
クレート指定
--lib
ライブラリコード
--bins
バイナリコード全て
--bin name
バイナリコード指定
--tests
テストコード全て
--test name
統合テストファイル指定

libtest コマンドのオプション

テスト対象を関数の単位で絞り込む (公式資料)。

最初の引数、testname が関数のパスに対するフィルタ文字列になる。

ここで、パスにはクレート名より後の部分を指定する (cargo 側との役割分担のため)。

なお、フィルタはデフォルトでは部分一致で行われるため注意。つまり、hogefoo_barhoge::piyo::fuga::foo_bar_baz() メソッドを対象とする。そうではなく、完全一致が必要となる場合、test-options の箇所にて --exact オプションを指定すればよい。

補足 (一意の指定)

cargo 側で複数の対象が選択され、それらそれぞれに libtest 側の条件に該当するものがあった場合、その全てがテスト対象になる。そのため、一意に限定するには両方の条件による絞り込みが必要。

ケーススタディ

ワークスペース全体


> cargo test --workspace

ライブラリテストの範囲指定


> cargo test --lib basic::api

テスト関数の個別指定


> cargo test --package my_crate funcPath -- --exact

結合テスト関数の指定


> cargo test --package my_crate --test my_test_file funcPath -- --exact

※ 結合テストの場合、funcPath が関数名のみになる場合が多い。

付録 (launch.json)

IDE に VSCode を使っている場合、よく使う起動構成を .vscode/launch.json ファイルに登録しておくと、テスト実行ボタンからすぐに実行できるため便利になる。

以下は上述の『結合テスト関数の指定』とだいたい同じになる登録例。


{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
			"name": "Custom test",
            "cargo": {
                "args": [
                    "test",
                    "--no-run",
					"--test=my_test_file",
					"--package=my_crate",
                ],
                "filter": {
                    "name": "my_test_file",
                    "kind": "test"
                }
            },
			"args": ["funcPath", "--exact"],
            "cwd": "${workspaceFolder}",
            "env": { "RUST_BACKTRACE": "1" }
        },

		// --  略 -- //
	]
}