skip to content

In Rust, what do `#[test]` and a `#[cfg(test)] mod tests` block do, and how do those tests reach a private helper function?

level: juniorimportance: must knowfreq 80%

answer

  1. compiled only for the test harness
  2. the tests module is just a module
  3. privacy flows down to descendants
  4. glob import of the parent's names

basics

~20 s

#[test] marks a no-argument function for the test harness; #[cfg(test)] compiles the tests module only in test builds. A child module may use its ancestors' private items, so use super::* lets tests call private helpers.

solid answer

~40 s

`#[test]` marks a function the test harness runs: a free function with no arguments and no type parameters, returning `()` or another `Termination` type such as `Result<(), E>`. `#[cfg(test)]` on the `tests` module means the module, its imports and its helpers are compiled only in test mode (`cargo test` or `rustc --test`), so `cargo build` leaves them out. The tests can call a private function like `round_half_even` because Rust lets a module and all its descendants use its private items, and `mod tests` is a child module. `use super::*` just brings the parent's names into scope; it bypasses nothing. Integration tests in `tests/` are separate crates and cannot do this.

code

rust · 32 lines
rust
/// Converts an amount in tenths of a cent to whole cents.
pub fn to_cents(tenths: i64) -> i64 {
    round_half_even(tenths)
}

// Private: not part of the crate's public API.
fn round_half_even(tenths: i64) -> i64 {
    let (q, r) = (tenths.div_euclid(10), tenths.rem_euclid(10));
    match r {
        0..5 => q,
        5 if q % 2 == 0 => q,
        _ => q + 1,
    }
}

#[cfg(test)]
mod tests {
    use super::*; // brings the private helper into scope

    #[test]
    fn halves_round_to_even() {
        assert_eq!(round_half_even(125), 12);
        assert_eq!(round_half_even(135), 14);
        assert_eq!(round_half_even(-125), -12);
    }

    #[test]
    fn non_halves_round_to_nearest() {
        assert_eq!(round_half_even(126), 13);
        assert_eq!(round_half_even(-126), -13);
    }
}

go deeper

for a junior

Recall the skeleton that cargo new --lib generates: a #[cfg(test)] mod tests, use super::* and #[test] functions, built by cargo test and skipped by cargo build.

for a middle

Explain the mechanics: test mode sets the test cfg and links the harness, a #[test] function takes no arguments, and privacy lets descendant modules use private items, which is why use super::* works.

for a senior

Show judgment: test private helpers in place instead of widening the API, keep fixtures under #[cfg(test)], and know which behaviour belongs in integration tests against the public API.

for a principal

Frame the cost for a codebase: tests on private helpers pin implementation details and make refactors noisier, so weigh them against testing through the public function.

## Unit tests live next to the code Rust's convention for **unit tests** is to put them in the same source file as the code they check, inside a module conventionally named `tests` and marked `#[cfg(test)]`. `cargo new --lib` generates exactly this skeleton. Take a **currency-rounding module**: its public `to_cents` function delegates to a private helper, `round_half_even`, which turns an amount in tenths of a cent into whole cents and sends exact halves to the even neighbour (12.5 becomes 12, 13.5 becomes 14). ```rust fn round_half_even(tenths: i64) -> i64 { let (q, r) = (tenths.div_euclid(10), tenths.rem_euclid(10)); match r { 0..5 => q, 5 if q % 2 == 0 => q, _ => q + 1, } } #[cfg(test)] mod tests { use super::*; #[test] fn halves_round_to_even() { assert_eq!(round_half_even(125), 12); assert_eq!(round_half_even(135), 14); } } ``` Two attributes do two different jobs here, and a third piece of the language, privacy, explains why the test can call a function that is not `pub`. ## What `#[test]` marks `#[test]` tells the compiler that a function is a **test case** for the built-in test harness (libtest). The Reference sets firm rules on what it may mark: - a **free function**, not a method, with **no arguments** and no type parameters; - not an `async fn` (rustc rejects it with "async functions cannot be used for tests"); - a return type that implements the `Termination` trait, which in practice means `()` or `Result<(), E>` where `E: Debug`. A test returning `()` passes if it finishes without panicking; one returning `Result<(), E>` passes if it returns `Ok(())`. Functions marked `#[test]` are compiled only in **test mode**. By default the harness runs the tests in parallel, on as many threads as the machine's available parallelism, and records a panic as that one test's failure while the rest keep running; the options that change this belong to Cargo's test command. ## What `#[cfg(test)]` adds Building in test mode (`cargo test`, or `rustc --test`) links the harness, generates a `main` that runs the tests, and turns on the `test` configuration option. `#[cfg(test)]` is ordinary conditional compilation keyed to that option, so the whole module disappears from every other build. | | `cargo build` | `cargo test` | |---|---|---| | `test` cfg option set | no | yes | | `#[test]` functions compiled | no | yes | | `#[cfg(test)] mod tests`, its imports and helpers | removed | compiled | | Test harness linked | no | yes | If the `#[test]` functions vanish anyway, why mark the module? Because the module itself, its `use super::*` line and any helper functions or fixtures inside it are **not** test functions. Without `#[cfg(test)]`, `cargo build` compiles them; rustc warns `unused import: super::*`, reports each unused helper function as never used, and even suggests adding `#[cfg(test)]` to the module. The attribute keeps test-only code out of the library you ship and saves compile time on normal builds. ## Why the tests can see private items Rust's privacy is based on modules: a private item may be used by the module that defines it **and by all of that module's descendants**. `mod tests` is a child of the module that defines `round_half_even`, so it may call the helper even though the helper is not `pub`. No special test rule is involved; the visibility levels themselves (`pub(crate)`, `pub(super)` and the rest) are covered with Rust's visibility rules. `use super::*` is only a **glob import** of the parent module's names. Delete it and the call fails with E0425, "cannot find function `round_half_even` in this scope", a name-resolution error rather than a privacy error. Writing `super::round_half_even(125)`, or importing it by path, works just as well. To test a private helper in place: 1. Leave the helper private; do not widen it to `pub` for the test's sake. 2. Add a `#[cfg(test)] mod tests` block in the same file. 3. Import the parent's names with `use super::*;`. 4. Write `#[test]` functions that call the helper and assert on its results. ## Keeping a test out of the default run `#[ignore]`, or `#[ignore = "needs the live exchange-rate feed"]`, sits beside `#[test]`. The function is still compiled in test mode but not executed; the harness lists it as `ignored`, with the reason when one is given. The harness flags `--ignored` (only ignored tests) and `--include-ignored` (everything) run it on demand, passed after `--` on the `cargo test` command line. ## Common mistakes - **Making a helper `pub` just to test it**, which widens the crate's API for no caller's benefit. - **Leaving out `#[cfg(test)]`**, so imports and test helpers are compiled into every build. - **Treating `use super::*` as a privacy escape hatch**; privacy already allowed the access. - **Expecting an integration test in `tests/` to reach private items**; those files are separate crates that see only the public API.

  • What changes if you delete `#[cfg(test)]` but keep the `#[test]` functions inside `mod tests`?
    The `#[test]` functions are still compiled only in test mode, but the module, its `use super::*` and any helper functions are now compiled in every build. `cargo build` then warns `unused import: super::*` and that the helpers are never used, and rustc suggests adding `#[cfg(test)]` to the module.
  • How do you keep a slow unit test in the module without running it on every test run?
    Add `#[ignore]`, or `#[ignore = "reason"]`, beside `#[test]`. The test is still compiled but not executed, and the harness reports it as ignored with the reason. Run it on demand with the harness flag `--ignored` or `--include-ignored`, passed after `--` to `cargo test`.
  • Could an integration test in the `tests/` directory call `round_half_even` the same way?
    No. Each file in `tests/` is compiled as its own crate that links the library from outside, so it sees only the library's public API. Private helpers are reachable only from inside the crate, which is why unit tests sit in a child module of the code.

  • A private function must be made pub or pub(crate) before any test can call it.
  • #[cfg(test)] is what turns a function into a test case.
  • Code under #[cfg(test)] ships in the release binary and is merely skipped at runtime.
  • use super::* is a special test import that switches off privacy checks.
  • Unit tests have to live in a separate file under tests/ to reach the code.