编写集成测试时如何从主 crate 访问函数?
当使用这样的测试创建项目时:
When creating a project with a test like so:
cargo init --bin projectname
mkdir projectname/tests
echo "extern crate projectname;" > projectname/tests/test.rs
cd projectname/
cargo build
我在测试时收到此错误:
I get this error when testing:
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 the functions in ´projectname/src/main.rs´ from projectname/tests/test.rs
?
如何从 projectname/tests/test.rs 访问projectname/src/main.rs"中的函数?
How can I access functions in ´projectname/src/main.rs´ from projectname/tests/test.rs?
你不能.
二进制文件不能用于外部 crate(就像你不能将 ELF 二进制文件用作共享对象/库一样)
A binary cannot be used a an external crate (the same way as you can't use a ELF binary as a shared object/library)
您只需要将初始化更改为
You just have to change your initialisation to
cargo init --lib projectname
或将您的 main.rs
重命名为 lib.rs
or rename your main.rs
to lib.rs
如果你真的想坚持一个主要的,你可以看看 同时包含库和二进制文件的 Rust 包?.
If you really want to stick with a main, you may look at Rust package with both a library and a binary?.