- Mastering Rust
- Rahul Sharma Vesa Kaihlavirta
- 282字
- 2021-07-02 13:35:27
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:

- 羅克韋爾ControlLogix系統(tǒng)應(yīng)用技術(shù)
- WSO2 Developer’s Guide
- PHP+MySQL網(wǎng)站開(kāi)發(fā)項(xiàng)目式教程
- Java編程技術(shù)與項(xiàng)目實(shí)戰(zhàn)(第2版)
- 青少年學(xué)Python(第1冊(cè))
- Visual FoxPro程序設(shè)計(jì)習(xí)題集及實(shí)驗(yàn)指導(dǎo)(第四版)
- iOS自動(dòng)化測(cè)試實(shí)戰(zhàn):基于Appium、Python與Pytest
- Statistical Application Development with R and Python(Second Edition)
- Buildbox 2.x Game Development
- R語(yǔ)言數(shù)據(jù)挖掘:實(shí)用項(xiàng)目解析
- Java程序設(shè)計(jì)教程
- 計(jì)算機(jī)組裝與維護(hù)(第二版)
- Python Linux系統(tǒng)管理與自動(dòng)化運(yùn)維
- HTML5 WebSocket權(quán)威指南
- Joomla!Search Engine Optimization