如何在不同的测试目录中使用 Rust 模块?

5

这是我的目录结构:

.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── add.rs
│   └── main.rs
└── tests
    └── add_test.rs

add.rs

pub fn add(a: u8, b: u8) -> u8 {
  return a + b;
}

main.rs

pub mod add;

fn main() {}

add_test.rs

#[cfg(test)]
mod tests {
  #[test]
  fn add_test() {
    // how do I use add.rs module?
  }
}

add_test函数中,我如何测试add.rsadd函数?


pub mod add?据我所知,库内部的任何内容都无法从外部进行测试。 - Netwave
tests/[test-file].rs 中,您不需要使用 #[cfg(test)],只需使用 #[test] 即可... 有关集成测试的更多信息。 - Nur
1个回答

4
注意你正在使用 mod add;。这不是公共模块,意味着在箱外不可用。
要使它在箱外可用(因此在测试中可用),您可以将模块公开,或重新导出函数本身。 此外,为此,您需要在 src 中有一个 lib.rs 文件,其中放置导出项:
// Make module public
pub mod add; 

// Make the function available at the root of the crate
pub use add::add; 

如果要在测试中使用您的函数,则可以像调用不同 Crate 的函数一样调用它。假设您的 Crate 名称为 your-crate:

// If your module is public
your-crate::add::add(2,3);

// If you reexport the function
your-crate::add(2,3);

在Rust书的测试组织章节中查看更多详细信息。


哦,是的,我错过了那个。但主要问题是如何在 tests/add_test.rs 中使用 add - Axel
编辑了如何调用它。 - Emoun
在我的情况下,Cargo.toml 中的名称是 ru。所以应该是 ru::add::add(2, 3) 对吧?如果是这样的话,那么它会显示 failed to resolve: use of undeclared crate or module ru - Axel
2
啊,你正在使用 main.rs,这意味着你的 crate 是一个二进制 crate。如果你再创建一个 lib.rs 文件,并以与 main.rs 相同的方式导出模块,它应该可以工作。我会更新答案。 - Emoun
只需使用rust-analyzer,它具有自动导入功能。 - Nur
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接