【问题标题】:How do I import submodules in another submodule which are part of the tests/ directory?如何在属于 tests/ 目录的另一个子模块中导入子模块?
【发布时间】:2022-01-26 19:34:22
【问题描述】:

我的目标是将test-module(tests/) 写入现有的 rust 包。

我的包目录树类似于下面的example_package

example_package
|
├── Cargo.toml
├── src
│   ├── lib.rs
|   ├── other_module.rs
│   ├── main.rs
└── tests
    ├── lib.rs
    ├── test1.rs
    └── test_fixtures
        ├── mod.rs
        ├── test_fixture1.rs
        └── test_fixture2.rs

这里

  • test-fixtures/ - 是实际测试用例中常用测试输入的目录。
  • test1.rs - 是导入 test-fixtures/ 并测试测试用例的实际测试用例。

但是当我尝试在test1.rs 中导入fixtures 时,如下所示

//tried all below three different ways
use crate::test_fixtures;
//use self::test_fixtures;
//use super::test_fixtures;

代码在编译时失败。

 --> tests/test1.rs:2:5
  |
2 | use crate::test_fixtures;
  |     ^^^^^^^^^^^^^^^^^^^^ no `test_fixtures` in the root

在属于tests/ 的另一个子模块中导入子模块的正确方法是什么?

代码:

// tests$ cat lib.rs 
pub mod test_fixtures;
pub mod test1;
// tests$ cat test_fixtures/mod.rs 
pub mod test_fixture1;
pub mod test_fixture2;
// tests$ cat test_fixtures/test_fixture1.rs 
pub fn test_fixture1() {
    
    print!("test_fixture1");
}
// tests$ cat test_fixtures/test_fixture2.rs 
pub fn test_fixture2() {
    
    print!("test_fixture2");
}
// tests$ cat test1.rs 
use crate::test_fixtures;
//use self::test_fixtures;
//use super::test_fixtures;
pub fn test1() {
    println!("running test1");
    
}

【问题讨论】:

    标签: rust rust-cargo


    【解决方案1】:

    这记录在书中,测试组织部分,Submodules in Integration Tests 小节:

    如前所述,tests 目录中的每个文件都被编译为自己独立的 crate。

    [...]

    在我们创建了 tests/common/mod.rs 之后,我们可以将它从任何集成测试文件中用作一个模块。下面是从 tests/integration_test.rs 中的 it_adds_two 测试调用 setup 函数的示例:

    use adder;
    
    mod common;
    
    #[test]
    fn it_adds_two() {
        common::setup();
        assert_eq!(4, adder::add_two(2));
    }
    

    注意mod通用;声明与我们在示例 7-21 中演示的模块声明相同。然后在测试函数中,我们可以调用common::setup()函数。

    【讨论】:

      【解决方案2】:
      └── tests
          ├── lib.rs
          ├── test1.rs
          └── test_fixtures
              ├── mod.rs
              ├── test_fixture1.rs
              └── test_fixture2.rs
      

      所呈现的文件结构做出了不正确的假设。 测试文件夹不是库包。在测试文件夹中添加一个名为 lib.rs 的文件将不会声明用于所有集成测试的模块。

      相反,在每个集成测试文件中声明公共模块(例如test_fixtures),或者创建一个由所有模块共享的帮助程序库。

      另见:

      【讨论】:

        【解决方案3】:

        您的tests/test1.rs 文件应如下所示,

        mod test_fixtures;
        
        #[test]
        fn test1() {
            test_fixtures::test_fixture2
        }
        
        

        注意,您需要使用mod 才能使用本地模块。

        这告诉 rust 编译器包含一个名为 test_fixtures.rs 的文件,或者查找其中包含 mod.rs 文件的 test_fixtures 文件夹。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-10
          • 2016-10-31
          相关资源
          最近更新 更多