The Rust docs mention that the #[test]
directive is for marking a function which is only compiled and executed in test mode. What is the reason for having the #[cfg(test)]
directive then?
#[cfg(test)]
, like any other #[cfg]
, can be applied to any piece of code (constant, module, function, statement...) and filters it out from compilation when not compiling tests. #[test]
applies only to functions, and in addition to removing the function when not compiling tests, it also registers it as a unit test.
You can use #[cfg(test)]
for example to not compile the whole module of the tests (to save compilation time), or to not compile test-only code such as test helpers or other testing logic in the crate.