Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to have a private function tested?

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?

like image 640
Sean Perry Avatar asked Jul 31 '15 18:07

Sean Perry


2 Answers

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.

like image 191
Shepmaster Avatar answered Sep 28 '22 10:09

Shepmaster


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.

like image 24
Mureinik Avatar answered Sep 28 '22 08:09

Mureinik