自動テストでのコンソール出力について。

プリントデバッグでよくある問題を取り上げる。

背景情報

自動テストとプリントデバッグには、以下のような相性問題がある。

解決策

VS Code + rust-analyzer + CodeLLDB の環境では以下が使える。

どちらの方法も cargo test コマンドに渡される以下のオプションを渡している。

解決策 1

settings.json ファイルの設定

この方法はユーザの環境全体に適用される。

サンプル


{
    "editor.inlayHints.enabled": "offUnlessPressed",
    "workbench.colorTheme": "Default Dark+",
    "diffEditor.ignoreTrimWhitespace": false,

    // -- 略 -- //

    "rust-analyzer.runnables.extraTestBinaryArgs": [
        "--nocapture"
    ],

    // -- 略 -- //
}

解決策 2

launch.json ファイルの設定

この方法は個別のテストの起動設定に適用される。
詳しくは、『cargo test での対象の指定 - 付録 (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", "--no-capture"],
            "cwd": "${workspaceFolder}",
            "env": { "RUST_BACKTRACE": "1" }
        },

        // -- 略 -- //
    ]
}