编写集成测试时如何访问主包中的函数?

How to access functions from the main crate when writing integration tests?

当创建一个带有测试的项目时:

cargo init --bin projectname
mkdir projectname/tests
echo "extern crate projectname;" > projectname/tests/test.rs
cd projectname/
cargo build

我在测试时遇到这个错误:

cargo test
   Compiling projectname v0.1.0 (file:///home/username/Lab/projectname)
error[E0463]: can't find crate for `projectname`
 --> tests/test.rs:1:1
  |
1 | extern crate projectname;
  | ^^^^^^^^^^^^^^^^^^^^^^^^^ can't find crate

如何从 projectname/tests/test.rs 访问“projectname/src/main.rs”中的函数?

How can I access functions in ´projectname/src/main.rs´ from projectname/tests/test.rs?

你不能。


二进制文件不能用作外部包装箱(就像您不能将 ELF 二进制文件用作共享文件一样 object/library)

您只需将初始化更改为

cargo init --lib projectname

或将您的 main.rs 重命名为 lib.rs

如果你真的想坚持主线,你可以看看Rust package with both a library and a binary?