如何从测试模块调用不在模块内部的函数? [英] How to call functions that aren't inside a module from the test module?

查看:49
本文介绍了如何从测试模块调用不在模块内部的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我的 src/lib.rs 文件的内容:

These are the contents of my src/lib.rs file:

pub fn foo() {}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        foo();
    }
}

当我运行 cargo test 时,出现以下错误:

When I run cargo test, I get the following error:

error[E0425]: cannot find function `foo` in this scope
 --> src/lib.rs:7:9
  |
7 |         foo();
  |         ^^^ not found in this scope

如何从 test 模块内部调用 foo?

How do I call foo from inside the test module?

推荐答案

您可以使用 super:: 来引用父模块:

You could use super:: to refer to the parent module:

fn it_works() {
    super::foo();
}

在 Rust 2015 中,您可以使用 :: 来引用 crate 的根模块:

In Rust 2015, you can use :: to refer to the root module of the crate:

fn it_works() {
    ::foo();
}

在 Rust 2018 中,您可以使用 crate:: 来引用 crate 的根模块:

In Rust 2018, you can use crate:: to refer to the root module of the crate:

fn it_works() {
    crate::foo();
}

或者,由于foo可能会被重复使用,你可以在模块中use它:

Or, as foo may be used repeatedly, you could use it in the module:

mod tests {
    use foo;         // <-- import the `foo` from the root module
    // or
    use super::foo;  // <-- import the `foo` from the parent module

    fn it_works() {
        foo();
    }
}

对于测试模块,从父模块导入所有内容也很常见:

For test modules, it's also common to import everything from the parent module:

mod tests {
    use super::*;  // <-- import everything from the parent module

    fn it_works() {
        foo();
    }
}

这篇关于如何从测试模块调用不在模块内部的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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