Unit testing Rust book单元测试示例导致死代码警告-为什么?
在学习Rust并试用Rust手册中与单元测试相关的示例代码时: 我得到了一个关于死代码的警告,这显然是由单元测试执行的。为什么呢 lib.rs中的代码Unit testing Rust book单元测试示例导致死代码警告-为什么?,unit-testing,rust,dead-code,Unit Testing,Rust,Dead Code,在学习Rust并试用Rust手册中与单元测试相关的示例代码时: 我得到了一个关于死代码的警告,这显然是由单元测试执行的。为什么呢 lib.rs中的代码 struct Rectangle { width: u32, height: u32, } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width &am
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(larger.can_hold(&smaller));
}
}
运行货物测试时的结果
$ cargo test
Compiling adder v0.1.0 (/Users/khorkrak/projects/rust/adder)
warning: associated function is never used: `can_hold`
--> src/lib.rs:8:8
|
8 | fn can_hold(&self, other: &Rectangle) -> bool {
| ^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: 1 warning emitted
Finished test [unoptimized + debuginfo] target(s) in 0.19s
Running target/debug/deps/adder-1082c4b063a8fbe6
running 1 test
test tests::larger_can_hold_smaller ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
$ rustc --version
rustc 1.50.0 (cb75ad5db 2021-02-10)
改变这个
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
这样,死代码警告就会消失
pub struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
pub fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
测试的结构和方法都需要公开。我注意到,如果运行指定--lib的测试,则不会出现这种情况。我仍然不清楚为什么在没有--lib的情况下它会这样工作。这能回答你的问题吗?“…真正的可执行文件中不需要只用于测试的代码,可能不应该包含这些代码。”不完全是这样,因为这些代码不仅仅是用于测试的代码。然而,答案就在最后的一条评论中:“因为其他的回答不是很明确,我自己也不得不重新发现这一点:如果你在你测试的库函数上得到一个死代码警告,一个常见的原因是你忘了把它标记为pub.-rspeer 7月18日19日21:49”遗憾的是,执行此操作后,即使未使用该功能,警告也不会再次出现