unit-testing - Rust book 单元测试示例导致死代码警告 - 为什么?
问题描述
在学习 Rust 并尝试 Rust 书中的示例单元测试相关代码时:https ://doc.rust-lang.org/book/ch11-01-writing-tests.html
我收到有关单元测试显然正在执行的死代码的警告。这是为什么?
lib.rs 中的代码
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
}
}
测试的结构和方法都需要公开。
推荐阅读
- r - 是否可以在 Tableau 上的 R 中执行 KS 测试?
- javascript - bootstrap 4 响应式导航汉堡按钮未关闭
- python - 如何在 Python 中遍历三个列表?
- angular - 不用每次都刷新页面就更新html文件的方法
- pine-script - 抵消交叉策略问题
- mongodb - MongoDB:对嵌套数组中的所有内容求和
- arrays - 为什么 Val 和 Var 对于 koltin 中的数组表现相同?
- python-3.x - NumPy:从 3 维数组中删除元素
- r - 删除时间序列之间的链接并在 ggplot 中的 x_axis 上添加次要日期刻度
- php - 验证不起作用,错误消息不会显示 Laravel 8