lilipo的编码小站

在 cargo test 中显示 println! 输出

发表于 2026-03-19

在 cargo test 中显示 println! 输出

在 Rust 中运行单元测试时,cargo test 默认会捕获测试的标准输出,因此 println! 的打印信息不会显示在终端中。如果需要查看这些输出,可以通过添加参数或设置环境变量来解决。

示例问题 `

#[test]
fn my_test() {
	println!("This is a test output.");
	assert_eq!(1 + 1, 2);
}

`

运行 cargo test 时,默认不会显示 println! 的输出。

解决方法

方法 1: 使用 --nocapture 参数

通过在命令中添加 -- --nocapture 参数,可以禁用输出捕获,从而显示 println! 的内容。 cargo test -- --nocapture

运行后,终端会显示如下内容:

running 1 test
This is a test output
test my_test ... ok

← 返回首页