How should Rust unit tests be organised?
Asked Answered
G

2

41

I have a number of methods in a mod. These methods need to be tested but they're private. I currently have the unit tests inside the same mod, but I'm not sure this is the right way to go about it, as I'm mixing two different things.

Should I put my unit tests in a different file? If so, how do I test private methods?

Gethsemane answered 3/8, 2014 at 17:58 Comment(0)
D
42

It's recommended to place tests in their own module. This module should be a child of the module whose code you want to test (and it can be defined in the same or different file).

#[cfg(test)]
mod tests {
    #[test]
    fn test_some_stuff() {
      // ... test code ...
    }
}

Private methods are not private to child modules, but you still need to import them with use super::some_name;.

By the way, this is all explained in the test organization section (11.3) of the Rust Book.

Debauchee answered 3/8, 2014 at 18:50 Comment(2)
Can you provide a directory structure as example?Overdo
@Overdo literally just src/the_file_with_code_and_tests.rsDonahue
O
0

There are different possibilities for Unit Tests in Rust.

You have this directory structure:

project_name/
    src/
       file.rs
       main.rs || lib.rs
    cargo.toml

Same file: simple and recommended

In Rust a file is module but you can declare a module inside a file with the mod keyword, children module can access parent private code (ex. your_function()):

fn your_function() {
    //...
}

#[cfg(test)]
mod tests {
    #[test]
    fn your_function_test() {}
}

Separate files hence modules

In your main.rs or lib.rs you declare the two modules

mod file;
#[cfg(test);
mod tests;

Then in your file.rs:

// !!! pub function since they are sibling modules 
// and by default in Rust all is private !!!
pub fn your_function() {
    //...
}

And in the tests.rs:

#[test]
fn your_function_test() {
    // ...
}

The concepts are practically the same, when you learn how Rust manages modules it's all easy. You just put a macro on top of the module declaration and that module is your test module. Different story for the integration tests.

Overdo answered 1/2 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.