简体   繁体   中英

How to use rust module inside a different test directory?

This is my directory structure,

.
├── 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?
  }
}

In add_test function how do I test add.rs 's add function?

Notice that you are using mod add; . This is not a public module meaning it is unavailable outside of your crate.

To have it available outside the crate (and therefore available in the test) you can either make the module public, or reexport the function itself. Additionally, to do this, you will need a lib.rs file in src where the exports are put:

// Make module public
pub mod add; 

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

To then use your function in tests, you call it the same way you would call a function for a different crate. Lets assume your crate was named your-crate :

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

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

See more details in the chapter on test organization in the Rust book .

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