Guidelines for Writing Rust Tests
Guidelines for writing new tests for Rust code.
Guidelines
- Test against the public API of the code under test.
- Test private APIs if and only if the private component is highly complex and difficult to test through the public API.
- Use
instawhenever you are testing output that is difficult to predict or compare. - Where appropriate, use
proptestto add property-based tests for key invariants. - Testing code should be written with the same care reserved to production code. Avoid unnecessary duplication, introduce helpers to reduce boilerplate and ensure readability. The intent of a test should be obvious or, if not possible, clearly documented.
- Do not reference exact line numbers in comments, as they may change over time.
Code organization
- Put tests for public (
pub) items under the crate'stestsdirectory. Two layouts are in use and both are fine — match whichever the crate already has:tests/integration/— one test crate with its ownmain.rsand a module per area (trie_rs,geo,query_eval, …). Prefer this for a new crate: it compiles as a single unit instead of one binary per file.- Cargo's default layout — one integration binary per
tests/*.rsfile (varint,fork_gc,rlookup, …).
- If the test must rely on private APIs, co-locate it with the code it tests, using a
#[cfg(test)]module. Integration tests cannot reachpub(crate)or private items, so this is the only option for them — but prefer exercising the behavior through the public API where you can, per guideline 2 above.
Dealing with extern C symbols
Check out CONTRIBUTING.md for instructions on how to deal with undefined C symbols in Rust tests.