简体   繁体   中英

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

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

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

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

You cannot.


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

or rename your main.rs to lib.rs

If you really want to stick with a main, you may look at Rust package with both a library and a binary? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM