Search code examples
rustintegration-testingdirectory-structure

What is the proper way to organize your code/tests in Rust?


In Chapter 11, section 3 (11.3) of the Rust book, it discusses the procedure for introducing integration tests into your project. In short, create a sibling directory to 'src' named 'tests' and locate your test code in a file in the 'tests' directory. The file contents from the example in the book are shown below:

 use adder;

#[test]
fn it_adds_two() {
    assert_eq!(4, adder::add_two(2));
}

The 'src/lib.rs' file has its code declared within a module:

mod adder {
  ...
}

This didn't work for me. I had to remove the module declaration in 'lib.rs' and add this ahead of the 'use adder;' declaration in my integration tests file:

extern crate adder;

So, I'm confused. Has something changed in the language and the docs haven't caught up yet? Is the code contained in a library ('src/lib.rs') not allowed to be organized into modules? If someone could point me to a comprehensive summary of code organization in Rust, that would be great. Thanks.


Solution

  • Make your src/lib.rs into:

    pub mod adder {
    ...
    }
    

    or if you have a module in a file called adder.rs, then just put pub mod adder;

    The important thing to note is that each file is a module and the pub keyword is needed to expose the module from the crate.

    Then in your integration tests files (under /tests/), do:

    use <cratename>::adder::<whatever you want to import or *>;
    
    fn main() {
    ...
    }