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);
}
阅读 2.8k
1 个回答

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

packages-and-crates

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进