Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust unit tests organization in sub-modules

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


// 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.

>Solution :

#[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)].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading