What is the purpose of grouping the tests in a `tests` module and is it possible to split them?
What is the purpose of grouping the tests in a tests
module like this
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_function_1() {
// test code for function 1 goes here
}
#[test]
fn test_function_2() {
// test code for function 2 goes here
}
}
and is it possible to split them and have the test functions outside of the tests
module?
#[test]
fn test_function_1() {
// test code for function 1 goes here
}
#[test]
fn test_function_2() {
// test code for function 2 goes here
}
I don't want to split them into their own directory.
1 answer
The important part here is the #[cfg(test)]
annotation.
The
#[cfg(test)]
annotation on the tests module tells Rust to compile and run the test code only when you runcargo test
, not when you runcargo build
. This saves compile time when you only want to build the library and saves space in the resulting compiled artifact because the tests are not included. You’ll see that because integration tests go in a different directory, they don’t need the#[cfg(test)]
annotation. However, because unit tests go in the same files as the code, you’ll use#[cfg(test)]
to specify that they shouldn’t be included in the compiled result.
As it says, it is just a way to separate tests from the library itself; the other way is to use a separate directory.
Creating tests outside of such a module actually does work, though from the wording I would assume doing so would have the test end up in the resulting binary, which may be undesirable.
0 comment threads