The Rust book says that using a "tests" module is the idiomatic way to have unit tests. But I cannot see a function from the super module in the tests module if that function is not marked 'pub'. How should one test internal functions then?
My first instinct was to look for a way to #ifdef
the keyword pub
. I have done this in the past for C++ testing. For Rust what I have done is simply have tests for private functions in the module and then tests for the public interface in the "tests" module.
Am I doing it right?
Nest your test module inside the module containing the private methods or structs:
mod inners {
fn my_func() -> u8 { 42 }
mod test {
#[test]
fn is_answer() {
assert_eq!(42, super::my_func());
}
}
}
Of course, I disagree that you should test private stuff in general, but thats a different discussion.
The idiomatic way to test a private function is not to. Unit tests are supposed to test a class' public behavior. Private methods are just implementation details of the aforementioned public methods which you should test.
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