gpt4 book ai didi

rust - 如何从 `src` 导入函数进行测试?

转载 作者:行者123 更新时间:2023-12-03 11:32:36 29 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to move tests into a separate file for binaries in Rust's Cargo?

(5 个回答)



How do I test private methods in Rust?

(2 个回答)



How do I access exported functions inside a crate's "tests" directory?

(2 个回答)



How to access functions from the main crate when writing integration tests?

(1 个回答)


1年前关闭。
社区在 4 个月前审查了是否重新打开此问题并将其关闭:

原始关闭原因未解决





几个小时以来,我一直试图了解如何导入函数以在 Rust 中进行测试,但没有成功。我有一个看起来像这样的项目结构:

.
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── main.rs
│ └── funcs
│ ├── mod.rs
│ └── hello.rs
└── tests
└── test_hello.rs
src/funcs/mod.rs :
pub mod hello;
src/funcs/hello.rs :
pub fn hello() {
println!("{}", "hello!");
}
src/main.rs :
mod funcs;

fn main() {
funcs::hello::hello(); // this works
}
src/tests/test_hello.rs
mod funcs; // this import does not work!

#[test]
fn add() {
assert_eq!(2 + 2, 4);
}

#[test]
fn hello_test() {
assert_eq!(funcs::hello::hello(), "hello");
}
如何在 src 中导入公共(public)函数以便它们可以在我的测试目录中使用?

最佳答案

创建 src/lib.rs文件以将包的大部分逻辑放入库箱并导出 funcs那里的模块:

pub mod funcs;
现在从您喜欢的任何地方使用库(包含模块)。在您的情况下,来自 src/main.rstests/test_hello.rs :
use <crate>::funcs;
替换 <crate>使用与包名称和根文件夹相同的库 crate 的名称。

关于rust - 如何从 `src` 导入函数进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63685938/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com