如何为内部 API 编写文档测试?

问题描述 投票:0回答:2

我正在编写一个包含私有结构和方法的库:

/// Constructs a new `Object`
///
/// Internal API
///
/// # Example
/// ```rust
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```

当我运行

cargo test
时,doctest 失败,因为
Object
是私有结构。

是否可以让它编译并运行

rust documentation
2个回答
0
投票

我认为如果你想让测试编译运行是不可能的,见this related question.

如果您只想将代码作为示例包含在文档中,而不尝试编译和运行它,您可以通过添加

ignore
标志将其从测试中排除:

/// ```rust,ignore
/// use lib::object::Object;
///
/// let tn = Object::new();
/// ```

0
投票

正如@Jmb 在其他答案中提到的,不,这是不可能的。但是我们可以对它进行单元测试,而不是忽略代码部分。

但是,我们可以对私有方法和结构进行单元测试。

cargo test
将测试 doctests 和 unittests,所以我们可以依赖它。我确定有一些方法可以将单元测试的覆盖范围包括到文档测试或所有测试指标(例如,在 Sonar 中)。

这是一个关于如何进行单元测试的例子

lib::object::Object

#[cfg(test)]
mod tests {
    use super::*; // imports all the items from the parent module, including our private Object struct

    #[test]
    fn test_object_new() {
        let tn = Object::new();
        // Add assertions here to test the `Object` struct.
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.