Home > Blockchain >  What is the difference between #[test] and #[cfg(test)] in Rust?
What is the difference between #[test] and #[cfg(test)] in Rust?

Time:11-20

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?

CodePudding user response:

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

CodePudding user response:

#[cfg(test)] tells the Rust compiler that the following code should only be compiled when the test configuration is active.

#[test] tells the Rust compiler that the following code should only be compiled when the test configuration is active and that the following function is a test.

E.g. you might have a helper function test_helper inside mod tests that does not test anything and should not be considered as a seperate test. So you want it to compile only for testing but not to be run as separate test by cargo test.

  • Related