如何在 VSCode 中使用自定义参数配置 cargo test

How to configure cargo test with custom arguments in VSCode

我有一些测试 create/read/write/delete 一个文件,我总是在每个文件中使用相同的文件名,因此我需要按顺序 运行 它们以避免同时对同一个文件进行操作。在命令行中我可以这样做

cargo test -- --test-threads=1

但是在 VSCode Run/Debug 菜单中它似乎不起作用。我将自动生成的配置与 Rust Analyzer 一起使用,加上这些额外的参数用于顺序 运行.

这是我的 launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug executable 'my-project'",
            "cargo": {
                "args": [
                    "build",
                    "--bin=my-project",
                    "--package=my-project"
                ],
                "filter": {
                    "name": "my-project",
                    "kind": "bin"
                }
            },
            "args": [],
            "cwd": "${workspaceFolder}"
        },
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug unit tests in executable 'my-project'",
            "cargo": {
                "args": [
                    "test",
                    "--no-run",
                    "--bin my-project",
                    "--package my-project",
                    "--", // here I've added the arguments
                    "--test-threads=1", // here I've added the arguments
                ],
                "filter": {
                    "name": "my-project",
                    "kind": "bin"
                }
            },
            "args": [],
            "cwd": "${workspaceFolder}"
        }
    ]
}

这是我在 运行 执行第二条命令(调用 cargo test 的命令)时得到的输出:

Running `cargo test --no-run --bin my-project --package my-project --message-format=json -- --test-threads=1`...
error: Found argument '--bin my-project' which wasn't expected, or isn't valid in this context

    Did you mean '--bin'?

    If you tried to supply `--bin my-project` as a value rather than a flag, use `-- --bin my-project`

USAGE:
    cargo.exe test --no-run --bin [<NAME>]

For more information try --help

VSCode 使用两步过程:

  1. 它调用 cargo test --no-run 来编译测试可执行文件并且
  2. 它直接调用测试可执行文件。

你应该把 --test-threads=1 放在最后一个 args 数组中:

{
    "type": "lldb",
    "request": "launch",
    "name": "Debug unit tests in executable 'my-project'",
    "cargo": {
        "args": [
            "test",
            "--no-run",
            "--bin=my-project",
            "--package=my-project",
        ],
        "filter": {
            "name": "my-project",
            "kind": "bin"
        }
    },
    "args": [ "--test-threads=1" ],
    "cwd": "${workspaceFolder}"
}