Cfg(test) vs test attribute

Hello,

I’ve always done the recommended setup for adding tests to a source file: make a tests submodule, cfg it out, and put your tests in there.

How does this compare to just dropping a function with #[test] at the end of the file? If you aren’t using and dev dependencies, and don’t require the use of any test code, is there a real difference?

The #[cfg(test)] attribute tells the compiler to ignore the item when not compiling tests. The #[test] attribute tells the compiler to run the function when cargo test is issued.

If your test doesn't have #[cfg(test)] on it, it is also compiled when building non-tests.

Actually #[test] also implies #[cfg(test)]. But it's common for real test cases to have bunch of support functions/constants/statics. If you don't wrap them with the #[cfg(test]-ed module they'll likely be included into the final binary.

6 Likes

Ah, interesting. I didn't know that.

2 Likes

Thanks! This is what I suspected. Sounds like just using #[test] when there are only test functions (no statics or helper functions) is just fine then.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.