How to test private methods in Rust?
In Rust, each module has its own tests submodule, which has access to the private functions of its parent module.Documentation tests are only run on public functions, since each documentation test is compiled as a separate binary that links to your library and can call its public API.
When using
#[test]
, there’s nothing special about private or public methods—you’re just writing perfectly normal functions that can access anything they can access.fn private_function() {
}
#[test]
fn test_private_function() {
private_function()
}
External tests, such as
tests/*.rs
and examples/*.rs
if you’re using Cargo, or doc tests, do not get access to private members; nor should they: such tests are designed to be public API tests, not to be dealing with implementation details.