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

老子叫甜甜 提交于 2020-01-03 15:23:12

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/31752882/what-is-the-idiomatic-way-to-have-a-private-function-tested

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!