官术网_书友最值得收藏!

Documentation tests

It's often a good practice to include code examples with any documentation for your crate's public APIs. There's a caveat in maintaining such examples, though. Your code might change and you might forget to update your examples. Documentation tests (doctests) are there to remind you to update your example code as well. Rust allows you to embed code in backticks within doc comments. Cargo can then run this example code that's been embedded within your documentation, and treats it as part of the unit test suite. This means that documentation examples run every time you run your unit tests, forcing you to update them. Quite amazing!

Documentation tests are also executed via Cargo. We have created a project called doctest_demo to illustrate documentation tests. In lib.rs, we have the following code:

// doctest_demo/src/lib.rs

//! This crate provides functionality for adding things
//!
//! # Examples
//! ```
//! use doctest_demo::sum;
//!
//! let work_a = 4;
//! let work_b = 34;
//! let total_work = sum(work_a, work_b);
//! ```

/// Sum two arguments
///
/// # Examples
///
/// ```
/// assert_eq!(doctest_demo::sum(1, 1), 2);
/// ```
pub fn sum(a: i8, b: i8) -> i8 {
a + b
}

As you can see, the difference between module-level and function-level doctests is not much. They are used in pretty much the same way. It is just that the module-level doctests show the overall usage of the crate, covering more than one API surface, while function-level doctests cover just the particular function over which they appear.

Documentation tests run with all the other tests when you run cargo test. Here's the output when we run cargo test in our doctest_demo crate:

主站蜘蛛池模板: 忻城县| 镇赉县| 河东区| 富宁县| 永福县| 大英县| 淅川县| 大余县| 哈尔滨市| 区。| 汕尾市| 江山市| 精河县| 进贤县| 余江县| 六枝特区| 修文县| 丽水市| 阿图什市| 扶风县| 蒙城县| 元阳县| 新源县| 温泉县| 灵武市| 陈巴尔虎旗| 黔西| 辉南县| 涟源市| 武宣县| 德庆县| 西华县| 东平县| 金寨县| 大关县| 株洲市| 前郭尔| 高台县| 东港市| 新巴尔虎右旗| 鸡西市|