Writing test and doc at once in Rust
Rust language allows inline documentation by writing triple slash comments (markdown syntax) just above the function signature and, of course, also unit testing.
See this introduction example:
|
|
Tests within the function documentation
But in Rust, it is possible to mix both concepts: tests within the function documentation in a code block (triple backticks, markdown syntax) and including the test assertions inside:
|
|
Note that a crate namespace (utils::
in this example) must be used to set
the crate location for the function (it is usually your project name).
Execute the tests
Now, cargo test
will scan and execute the Doc-tests:
Generate documentation
To generate the documentation, you use the cargo doc
command. It will create
the documentation under the subdirectory target/doc/utils
:
You have probably observed many examples in The Rust Standard Library documentation that include test assertions. Now, you can imaging the reason why they are there.