Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put these tests in a separate file?

Tags:

testing

rust

In main.rs, I have some functions that I created to reduce the size of main(). Inside them, I use structs and their methods.

fn handle_input() {
  // some code
}

fn handle_quit() {
  // some code
) {

fn main() {
   // handle_handle_input() being is used here
   // handle_quit() being is used here
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_handle_input() {
        // some code
    }

    #[test]
    fn test_handle_quit() {
        // some code
    }
}

Right now, all the tests are passing. However, main.rs is becoming too big, so I want to place the tests in their own file.

How can I accomplish this, since I can no longer use use super::*? Or maybe the only way is to convert these functions into struct methods and import them in the new test file?

like image 474
alexchenco Avatar asked Oct 11 '25 12:10

alexchenco


1 Answers

You can replace the module declaration with

#[cfg(test)]
mod tests;

and then move the tests into the file tests.rs in the same directory as main.rs. The file name must match the module name in the declaration above. The file tests.rs should contain everything inside the curly braces after mod tests in your code, excluding the braces.

Generally, having code and tests in the same file is common and intended in Rust, so you could consider splitting up your files into modules in a different way.

like image 94
Sven Marnach Avatar answered Oct 14 '25 02:10

Sven Marnach