繁体   English   中英

如何在Windows上调试Rust单元测试?

[英]How to debug Rust unit tests on Windows?

我正在使用带有Rust和Visual Studio工具链的Windows上的VS代码开发Codingame问题的代码。

我找到了多个指南,解释了如何调试cargo build生成的可执行文件,最好的是使用Visual Studio Code和MSVC Debugger在Windows调试Rust

但是,当我遇到问题时,我倾向于编写单元测试(我已经在Java,JavaScript,Ruby等中完成了这些测试),然后我会进行调试。 不幸的是,我无法在Rust中找到任何方法。 如何配置环境以调试我的测试?

我不是在谈论添加println! 我的测试中的陈述,因为我已经知道如何做到这一点。 我也不是在谈论添加新断言,因为它们存在于测试中,而不是测试代码中。

我想要的是在我的测试调用的代码上使用VS Code Debugger。

Rust单元测试被编译为单独的二进制文件,这意味着您调试它们与任何其他二进制文件完全相同 编译后,它们位于./target/debug/$name-$hash

Visual Studio代码

这是VS Code配置文件的修改版本,允许我调试单元测试。

tasks.json

{
    "type": "shell",
    "label": "cargo test build",
    "command": "cargo",
    "args": [
        "test", "--no-run"
    ],
    "problemMatcher": [
        "$rustc"
    ]
}

launch.json

{
    "name": "Run Test Debugger",
    "type": "cppvsdbg",
    "request": "launch",
    "program": "${workspaceFolder}/target/debug/buggin-70708b3916187eeb.exe",
    "args": [],
    "stopAtEntry": false,
    "cwd": "${workspaceFolder}",
    "environment": [],
    "externalConsole": true,
    "preLaunchTask": "cargo test build",
}

工作

VS Code调试器在测试中运行

WinDbg的

构建测试:

cargo test --no-run

在Windbg中打开构建的可执行文件并打开源文件。

在Rust测试的Windbg


查找哈希是最烦人的方面。 我所知道的最好的解决方案是编写一个构建测试的小脚本,然后找到最新的测试可执行文件。 我的Powershell技能不足以完成任务,也不知道如何将其与VS Code或Windbg直接集成。

Cargo有一些未解决的问题可以帮助识别文件:

你可以使用println! 调试

#[test]
fn test_false() {
    println!("This test is not OK");
    assert!(1 == 2);
}

或者使用assert宏来提供自定义消息。

#[test]
fn test_complex() {
    let a = vec![1, 2];
    let b = vec![3, 4, 5];
    assert!(a.len() == b.len(), "Mismatch between vec lenghts! ({} - {})", a.len(), b.len());
}

这将导致

cargo test
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running target/debug/deps/foo-3cf890b7dd22d797

running 3 tests
test test_complex ... FAILED
test test_false ... FAILED
test test_true ... ok

failures:

---- test_complex stdout ----
thread 'test_complex' panicked at 'Mismatch between vec lenghts! (2 - 3)', src/main.rs:21:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.

---- test_false stdout ----
This test is not OK
thread 'test_false' panicked at 'assertion failed: 1 == 2', src/main.rs:14:5


failures:
    test_complex
    test_false

test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out

error: test failed, to rerun pass '--bin foo'

注意:第三个好的案例也有println! 在它,但它不会出现,因为测试是成功的。

通常,您的测试用例应该总是那么简单,不需要调试您的测试用例,而是您的代码。 但我猜这是理论:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM