2017-10-21 56 views
0

我正試圖在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 
+0

我刪除了'pub mod potter',錯誤仍在繼續。 –

+0

我從重複的答案中應用瞭解決方案,它似乎不起作用。 –

+0

我將potter.rs重命名爲lib.rs,但它一直不工作... –

回答

5

回去和reread The Rust Programming Language about modules and the filesystem

常見痛點:

  • 每一種編程語言都有自己的處理文件的方式 - 你不能只是假設,因爲你使用任何其他語言,你會奇蹟般地得到它鏽病的起飛。這就是爲什麼你應該go back and re-read the book chapter on it

  • 每個文件定義一個模塊。您的lib.rs定義了一個與您的箱子名稱相同的模塊;一個mod.rs定義一個與它所在的目錄同名的模塊;每個其他文件都定義了文件名稱的模塊。

  • 您的圖書館板條箱的根目錄必須爲lib.rs;二進制箱子可以使用main.rs

  • 不,你真的不應該試圖做非慣用的文件系統組織。有許多技巧可以做你想做的任何事情;除非你已經是一個先進的Rust用戶,否則這些都是可怕的想法。

  • 地道的Rust通常不會像許多其他語言一樣將「每個文件一種類型」。對真的。你可以在一個文件中有多個東西。

  • 單元測試通常與其正在測試的代碼位於同一個文件中。有時他們會被分成一個子模塊,但這並不常見。

  • 集成測試,示例,基準都必須像箱子的任何其他用戶一樣導入箱子,並且只能使用公共API。


要解決您的問題:

  1. 將您src/potter.rssrc/lib.rs
  2. src/lib.rs刪除pub mod potter。不需要嚴格的,但可以消除不必要的模塊嵌套。
  3. extern crate potter添加到您的集成測試tests/tests.rs

文件系統

├── 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); 
}