Reputation: 3886
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?
Upvotes: 6
Views: 2588
Reputation: 430665
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.
Upvotes: 6
Reputation: 311188
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.
Upvotes: 2