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

car*_*aez 3 rust

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

我的结构是:

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

和我的 Cargo.toml

[package]
name = "potter"
version = "0.1.0"
authors = ["my name"]
[dependencies]
Run Code Online (Sandbox Code Playgroud)

我的potter.rs包含:

pub mod potter {
    pub struct Potter {

    }

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

}
Run Code Online (Sandbox Code Playgroud)

我的tests.rs包含:

use potter::Potter;

    #[test]
    fn it_works() {

        let pot = potter::Potter::new();
        assert_eq!(2 + 2, 4);
    }
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

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
Run Code Online (Sandbox Code Playgroud)

如果我添加extern crate potter;,它不会修复任何东西......

error[E0463]: can't find crate for `potter`
 --> tests/tests.rs:1:1
  |
1 | extern crate potter;
  | ^^^^^^^^^^^^^^^^^^^^ can't find crate
Run Code Online (Sandbox Code Playgroud)

She*_*ter 13

返回并重读关于模块和文件系统的Rust编程语言.

常见的痛点:

  • 每种编程语言都有自己的处理文件的方式 - 你不能只是假设因为你已经使用了任何其他语言,你会神奇地得到Rust的看法.这就是为什么你应该回去重新阅读关于它的书章.

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

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

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

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

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

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


要解决您的问题:

  1. 移动你src/potter.rssrc/lib.rs.
  2. pub mod potter从中移除src/lib.rs.不是严格要求,但删除了不必要的模块嵌套.
  3. 添加extern crate potter到集成测试tests/tests.rs.

文件系统

??? Cargo.lock
??? Cargo.toml
??? src
?   ??? lib.rs
??? target
??? tests
    ??? tests.rs
Run Code Online (Sandbox Code Playgroud)

SRC/lib.rs

pub struct Potter {}

impl Potter {
    pub fn new() -> Potter {
       Potter {}
    }
}
Run Code Online (Sandbox Code Playgroud)

测试/ tests.rs

extern crate potter;

use potter::Potter;

#[test]
fn it_works() {
    let pot = Potter::new();
    assert_eq!(2 + 2, 4);
}
Run Code Online (Sandbox Code Playgroud)

  • “单元测试通常与其测试的代码位于同一个文件中。” 这绝对是狂野的。人们真的认为它可以维护吗? (3认同)
  • 我将所有内容从 `tests/common.rs` 移动到 `tests/common/mod.rs`,现在我可以在其他测试文件中执行 `mod common;`。有用。谢谢您的帮助。 (2认同)
  • @马修迪恩是的。 (2认同)