无法在集成测试中导入模块

时间:2017-10-21 20:16:51

标签: rust

我正在尝试在Rust中配置一个示例项目。

我的结构是:

  • src/potter.rs
  • tests/tests.rs

我的Cargo.toml

[package]
name = "potter"
version = "0.1.0"
authors = ["my name"]
[dependencies]

我的potter.rs包含:

pub mod potter {
    pub struct Potter {

    }

    impl Potter  {
        pub fn new() -> Potter {
         return Potter {};
        }
    }

}

我的tests.rs包含:

use potter::Potter;

    #[test]
    fn it_works() {

        let pot = potter::Potter::new();
        assert_eq!(2 + 2, 4);
    }

但是我收到了这个错误:

error[E0432]: unresolved import `potter`
 --> tests/tests.rs:1:5
  |
1 | use potter::Potter;
  |     ^^^^^^ Maybe a missing `extern crate potter;`?

error[E0433]: failed to resolve. Use of undeclared type or module `potter`
 --> tests/tests.rs:6:19
  |
6 |         let pot = potter::Potter::new();
  |                   ^^^^^^ Use of undeclared type or module `potter`

warning: unused import: `potter::Potter`
 --> tests/tests.rs:1:5
  |
1 | use potter::Potter;
  |     ^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_imports)] on by default

如果我添加extern crate potter;,则无法修复任何内容......

error[E0463]: can't find crate for `potter`
 --> tests/tests.rs:1:1
  |
1 | extern crate potter;
  | ^^^^^^^^^^^^^^^^^^^^ can't find crate

1 个答案:

答案 0 :(得分:10)

返回reread The Rust Programming Language about modules and the filesystem

常见的痛点:

  • 每种编程语言都有自己的处理文件的方法 - 你不能只是假设因为你使用过任何其他语言,你会神奇地让Rust接受它。这就是为什么你应该go back and re-read the book chapter on it

  • 每个文件定义一个模块。您的lib.rs定义了与您的箱子同名的模块; a mod.rs定义一个与其所在目录同名的模块;每隔一个文件定义一个文件名的模块。

  • 您的图书馆包的根必须lib.rs;二进制包可以使用main.rs

  • 不,你真的不应该尝试做非惯用的文件系统组织。有一些技巧可以做你想要的任何事情;除非您已经是高级Rust用户,否则这些都是糟糕的想法。

  • Idiomatic Rust通常不会像许多其他语言一样放置“每个文件一种类型”。对真的。您可以在一个文件中包含多个内容。

  • 单元测试通常与它正在测试的代码存在于同一个文件中。有时候它们会分成一个子模块,但这种情况并不常见。

  • 集成测试,示例,基准测试都必须像包装箱的任何其他用户一样导入包装箱,并且只能使用公共API。

解决问题:

  1. 将您的src/potter.rs移至src/lib.rs
  2. pub mod potter移除src/lib.rs。不需要严格,但删除了不必要的模块嵌套。
  3. extern crate potter添加到您的集成测试tests/tests.rs
  4. <强>的文件系统

    ├── Cargo.lock
    ├── Cargo.toml
    ├── src
    │   └── lib.rs
    ├── target
    └── tests
        └── tests.rs
    

    <强>的src / lib.rs

    pub struct Potter {}
    
    impl Potter {
        pub fn new() -> Potter {
           Potter {}
        }
    }
    

    <强>测试/ tests.rs

    extern crate potter;
    
    use potter::Potter;
    
    #[test]
    fn it_works() {
        let pot = Potter::new();
        assert_eq!(2 + 2, 4);
    }