Home > Back-end >  Rust unit tests organization in sub-modules
Rust unit tests organization in sub-modules

Time:09-04

I want to better organize my unit tests inside a rust file.

This file contains plenty of functions and their variations, and i would like to organize "submodules" for testing, but i don't know if it makes sense in Rust with cargo.

I want to do something like


// fn etc, etc

#[cfg(test)]
mod tests{
  use super::*;
  mod test_a {
    use super::*;
    #[test]
    fn a_panics(){ }
    // etc
  }
  mod test_b {
    use super::*;
    #[test]
    fn b_panics(){}
    // etc
  }
}

But I'm unsure how would i have to go about this.

Should every module be annotated with #[cfg(test)] or just the top tests one?

I suppose it works because in vscode the codelens shows the >Run Tests | Debug lens on tests and each submodule, but still I'm unsure about the module annotations or if this is good practice in rust, since i couldn't find any example of this online.

CodePudding user response:

#[cfg(test)] just tell the compiler to not compile the module (and everything inside) if we're not testing. This is done solely to save compilation time.

Since it works for everything inside too, there's no need to mark nested modules as #[cfg(test)].

  • Related