How do I test private methods in Rust? I didn't find any information about it. There's no information in the documentation either.
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.
I don't know if this issue is still open for you, but I found some documentation about it :
Test Organization
What I retained from it is that you can test private method but only if the test can see it (i.e. they are in the same scope), since tests follow the visibility rules as any other function.
Here is a working example :
pub fn add_two(a: i32) -> i32 { internal_adder(a, 2) } fn internal_adder(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { use super::*; #[test] fn internal() { assert_eq!(4, internal_adder(2, 2)); } }
All in all, please remember that the debate wether private methods should or should not be tested is still open within the test community. Both sides have valid argument and the correct answer only relies on you, your vision on testing procedure and the context of your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With