Rust 编写测试是否可以引入 main 文件中的函数 ?
如题最近在学习 Rust
然后尝试在 test
目录的测试文件中使用 main
文件里定义的函数但是报错:
error[E0433]: failed to resolve: there are too many leading `super` keywords
--> tests\integration_test.rs:1:5
|
1 | use super::*;
| ^^^^^ there are too many leading `super` keywords
求教能这么操作么?还是一定要放到 lib
目录里然后搞个模块:(代码如下)
main.rs
fn main() {
}
fn scope_test() -> i32 {
return 100;
}
tests/test_a.rs
use super::*;
#[test]
fn test_a() {
println!("A");
assert_eq!(scope_test(), 100);
}
回复
1个回答

test
2024-07-16
1. 可以在main.rs 写测试
fn main() {
println!("Hello, world!");
}
pub fn fn_in_main() {
println!("Fun in main");
}
#[cfg(test)]
mod test_in_main {
#[test]
fn test_in_main(){
super::fn_in_main(); //or crate::fn_in_main();
}
}
2. 把main.rs引入到tests下的 test_a mod 中进行测试
下面要注意的是 tests/test_a mod 的位置 以及 tests是在src下;
stephanie@klde hello_w % tree -L 3
.
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── main.rs
│ └── tests
│ ├── mod.rs
│ └── test_a.rs
└── target
├── CACHEDIR.TAG
└── debug
├── build
├── deps
├── examples
├── hello_w
├── hello_w.d
└── incremental
Codes in src/tests/mod.rs
//声明模块
pub mod test_a; //声明到 module tree 中; 路径为 crate::tests::test_a
Codes in src/tests/test_a.rs
#[cfg(test)]
mod test_a {
#[test]
fn funtion_in_main(){
crate::fn_in_main();
}
}
Codes in src/mian.rs 注意 fn_in_main 声明为pub
mod tests; //声明到 module tree 中; 路径为 crate::tests
fn main() {
println!("Hello, world!");
}
pub fn fn_in_main() {
println!("Fun in main");
}
3. 引入lib.rs 还在src/tests/test_a 进行测试
stephanie@klde hello_w % tree -L 3
.
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── main.rs
│ └── tests
│ ├── mod.rs
│ └── test_a.rs
└── target
├── CACHEDIR.TAG
└── debug
├── build
├── deps
├── examples
├── hello_w
├── hello_w.d
└── incremental
Codes in main.rs
fn main() {
println!("Hello, world!");
}
pub fn fn_in_main() {
println!("Fun in main");
}
Codes in lib.rs
mod main;
mod tests;
Codes in tests/mod.rs
pub mod test_a;
Codes in tests/test_a.rs;
#[cfg(test)]
mod test_a {
use crate::main::fn_in_main; //crate is hello_w
#[test]
fn funtion_in_main(){
fn_in_main();
}
}
Refs
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容