测试私有功能的惯用方式是什么? [英] What is the idiomatic way to have a private function tested?

查看:47
本文介绍了测试私有功能的惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust书,测试"模块是进行单元测试的惯用方式.但是,如果该功能未标记为"pub",则无法从超级模块中的功能中看到该功能.那么应该如何测试内部功能?

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?

我的第一个直觉是寻找一种方法来对关键字 pub 进行 #ifdef .过去,我在进行C ++测试时就这样做了.对于Rust,我要做的只是在模块中测试私有功能,然后在测试"模块中测试公共接口.

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.

我做对了吗?

推荐答案

将测试模块嵌套在包含私有方法或结构的模块中:

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.

这篇关于测试私有功能的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆