简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM