Milkncookiez
Milkncookiez

Reputation: 7397

Module cannot be found from tests dir

I have the following structure:

root/
  |--src/
    |--main.rs
    |--api.rs
  |--tests/
    |--my_test.rs
  |--Cargo.lock
  |--Cargo.toml

The crate's main file is root/src/main.rs and in that main file I have:

pub mod api;
pub use api::*;

But when I try to import the api in the test file like so:

use crate::src::api::*;

// also tried `use crate::api::*;`

I get the error that the import cannot be found. How do I make the source file visible to the tests file?

I'd like to keep the tests separate from the implementation.

Upvotes: 0

Views: 282

Answers (1)

cafce25
cafce25

Reputation: 27401

Integration-testing is only supported for [lib] crates, not binary crates such as the one created for src/main.rs, you should put all code that you want to test into a library crate (src/lib.rs) or it's modules and import them like you would with an external crate using the crates name.

So with a simple src/lib.rs which you can just add to your project and will be automatically detected by cargo

pub mod api;

you can then use it from src/main.rs or your tests/my_test.rs like this

use crate_name::api::*;

where crate_name is the one you specify in your Cargo.toml

Upvotes: 3

Related Questions