testing - 如何在 Rust 的实现中测试方法

标签 testing methods rust

<分区>

我正在尝试增加我的 Rust 应用程序中的测试覆盖率。我已经阅读了很多关于测试公共(public)功能和测试私有(private)功能以及添加“测试”目录以添加集成测试的内容。但我还没有阅读任何关于在实现中测试方法的内容。我已经尝试为此进行谷歌搜索,但我没有找到任何东西。

这是一个简单的例子,这就是我实现测试的方式吗?

struct Rectangle {
    width: usize,
    length: usize,
}

impl Rectangle {
    pub fn new(width: usize, length: usize) -> Rectangle {
        Rectangle {
            width,
            length,
        }
    }

    fn area(&mut self) -> usize {
        self.width * self.length
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rectangle() {
        let mut rectangle = Rectangle::new(4, 5);
        
        assert_eq!(20, rectangle.area())
    }
}

最佳答案

是的,这正是您要测试结构方法的方式。 Rust 书有一章叫做 Test Organization其中指出:

The purpose of unit tests is to test each unit of code in isolation from the rest of the code to quickly pinpoint where code is and isn’t working as expected. You’ll put unit tests in the src directory in each file with the code that they’re testing. The convention is to create a module named tests in each file to contain the test functions and to annotate the module with cfg(test).

另一种常见的测试组织方法是使用 documentation tests . rustdoc 支持将您的文档示例作为测试执行。因此,在下面的示例中运行 cargo test 将导致 area 函数作为测试执行:

impl Rectangle {
    /// ```rust
    /// use crate::Rectangle;
    ///
    /// let mut rectangle = Rectangle::new(4, 5);
    /// assert_eq!(20, rectangle.area())
    /// ```
    fn area(&mut self) -> usize {
        self.width * self.length
    }
}

关于testing - 如何在 Rust 的实现中测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65193714/

相关文章:

c# - 无法从 C# WPF 中的另一个窗口调用方法

c# - 从 MethodInfo 生成 DynamicMethod

java - 输出空白——计算数组平均值的Java程序

rust - 如何用 `if` 重写将整数与值进行比较的 `match` 链?

generics - 当参数不受约束时,如何为实现特征 Fn 的类型指定通用参数?

azure - 如何使用 Azure DevOps 监控测试进度?

javascript - 如何在 appium 的 webdriverio 中使用驱动程序对象

安卓测试 : updating listview in a broadcast receiver onreceive

java - 如何测试junit5中的日志记录?

rust - 为什么闭包会引入借用,而内联的相同代码却不会引入借用?