cargo test でのテスト対象の指定方法について。
cargo test[options] [testname] [--test-options]
コマンドは二段構成になっている。
options までは cargo が自分で処理する。
testname 以降はテスト実行機能 libtest に渡される。
cargo コマンドのオプションテスト対象をビルド成果物の単位で絞り込む (公式資料)。
以下は代表的なオプションの抜粋。
--workspace--package name--lib--bins--bin name--tests--test namelibtest コマンドのオプションテスト対象を関数の単位で絞り込む (公式資料)。
最初の引数、testname が関数のパスに対するフィルタ文字列になる。
ここで、パスにはクレート名より後の部分を指定する (cargo 側との役割分担のため)。
なお、フィルタはデフォルトでは部分一致で行われるため注意。つまり、hoge や foo_bar は hoge:: メソッドを対象とする。そうではなく、完全一致が必要となる場合、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" }
},
// -- 略 -- //
]
}