Writing Tests

Writing Tests in Rust: Nothing goes onto the shelves straight off the lorry. It goes onto a bench, where somebody with the order in one hand and the item in…

The Analogy: The Goods-In Bench

Nothing goes onto the shelves straight off the lorry. It goes onto a bench, where somebody with the order in one hand and the item in the other asks a short list of very specific questions: is this the part that was ordered, are there forty of them, does this one pass through the gauge. Every question has an expected answer, and the expected answer was written down before the item arrived.

The questions are deliberately small and deliberately independent. A wrong part number does not stop anyone counting the box, and what goes back to the supplier is a per-item report -- line 3 is the wrong part, line 7 is short by two, everything else is fine -- rather than a verdict on the delivery as a whole. Rust runs tests the same way: each one is its own function, one failing does not prevent the rest from running, and the summary names every failure separately.

Some checks run the other way round. The bench also has to prove that it catches things, so a known-bad sample is put through on purpose and the correct outcome is a rejection. A bench that quietly accepted the bad sample would be worse than no bench at all, because everyone would trust it. Rust has an attribute for exactly this shape of test.

And the bench is not part of what you sell. The gauges, the clipboards, the person holding the order -- none of it goes out on the delivery van. It exists inside the building, at one specific stage, and the customer never sees it. That separation is written into the language: test code carries a marker meaning "compile this when testing and leave it out of the thing I ship".


Syntax or Core Structure

Tests are ordinary functions with an attribute, gathered in a module with an attribute of its own:

pub fn gauge(width_mm: u32) -> bool {
    width_mm >= 10 && width_mm <= 40
}

pub fn short_by(ordered: u32, received: u32) -> u32 {
    if received >= ordered {
        0
    } else {
        ordered - received
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accepts_a_width_in_range() {
        assert!(gauge(25));
    }

    #[test]
    fn rejects_a_width_that_is_too_wide() {
        assert!(!gauge(41));
    }

    #[test]
    fn reports_the_shortfall() {
        assert_eq!(short_by(40, 38), 2);
    }

    #[test]
    fn a_surplus_is_not_a_shortfall() {
        assert_eq!(short_by(40, 44), 0);
    }
}
cargo test

Output:

running 4 tests
test tests::accepts_a_width_in_range ... ok
test tests::a_surplus_is_not_a_shortfall ... ok
test tests::rejects_a_width_that_is_too_wide ... ok
test tests::reports_the_shortfall ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Two details about that output before anything else. The lines appear in whatever order the tests finish, because they run in parallel by default, so a second run may list them differently -- there is nothing wrong when that happens. And the real last line ends with a finished in figure that is left out here, since it is a measurement of your machine and not of your code.

Three pieces of syntax are doing all the work. #[test] marks a function as a test, and a test passes by returning without panicking. #[cfg(test)] on the module means the whole thing is only compiled when you run cargo test -- during cargo build it is as if the module were not in the file, so it adds nothing to the shipped binary and cannot slow it down. use super::*; pulls in everything from the surrounding module, which is what lets the tests call gauge and short_by by their bare names.

MacroPasses whenNeeds of the valuesOn failure it shows
assert!(cond)cond is trueNothingThe source text of the expression
assert_eq!(a, b)a == bPartialEq and DebugBoth values, labelled left and right
assert_ne!(a, b)a != bPartialEq and DebugBoth values
panic!("...")NeverNothingYour message, and the test fails

That second row is a trait bound in the standard library's own code, and Module 6 is why the error makes sense when it is not satisfied: assert_eq! needs PartialEq to compare and Debug to print, so comparing a struct without #[derive(Debug)] fails to compile with a bound error rather than a failed test.


Technical Depth: What A Failure Reports, And The Other Kinds Of Test

Reading a failure

The report is the whole product of a failing test, so it is worth knowing what is in it. Take a deliberately wrong gauge check, numbered as it would sit in src/lib.rs:

pub fn fits(width_mm: u32, gauge_mm: u32) -> bool {
    width_mm < gauge_mm
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exact_width_fits() {
        assert!(fits(40, 40), "a 40mm part should pass a 40mm gauge");
    }
}

Output:

running 1 test
test tests::exact_width_fits ... FAILED

failures:

---- tests::exact_width_fits stdout ----
thread 'tests::exact_width_fits' panicked at src/lib.rs:11:9:
a 40mm part should pass a 40mm gauge
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

failures:
    tests::exact_width_fits

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

The file, line and column point at the assertion, the test name appears twice -- once in the running list and once in the summary of failures -- and the optional message after the condition is what a reader gets instead of the bare source text. A test failing in six months is read by somebody who did not write it, and that message is the only chance to explain what was supposed to be true.

assert_eq! produces a better report without needing a message, because it can print both sides. Change the shortfall test to expect the wrong number:

    #[test]
    fn reports_the_shortfall() {
        assert_eq!(short_by(40, 38), 3);
    }

Output:

assertion `left == right` failed
  left: 2
 right: 3

That is why assert_eq!(a, b) is preferred over assert!(a == b), which would only report that the expression was false. The convention is that the left argument is what the code produced and the right is what you expected, so the two labels read as "got" and "wanted" -- the macro does not care, but every reader will assume it.

Testing that something is refused

pub fn set_gauge(mm: u32) -> u32 {
    if mm == 0 {
        panic!("gauge must be greater than zero");
    }

    mm
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_valid_gauge_is_returned() {
        assert_eq!(set_gauge(40), 40);
    }

    #[test]
    #[should_panic]
    fn zero_is_rejected() {
        set_gauge(0);
    }

    #[test]
    #[should_panic(expected = "greater than zero")]
    fn zero_is_rejected_for_the_stated_reason() {
        set_gauge(0);
    }
}

Output:

running 3 tests
test tests::a_valid_gauge_is_returned ... ok
test tests::zero_is_rejected ... ok
test tests::zero_is_rejected_for_the_stated_reason ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The first should_panic test is weaker than it looks. It passes if the function panics for any reason at all, including an index out of bounds introduced by a later edit that has nothing to do with validation -- the test would keep passing while testing something else entirely. The expected form checks that the panic message contains that substring, which pins the test to the reason. It is a substring match and not an equality check, so a short distinctive fragment is the right thing to put there.

Tests that return Result

A test may return Result<(), E>, in which case Err fails it. The reason to want this is ?:

    #[test]
    fn parses_a_width() -> Result<(), String> {
        let width: u32 = match "25".parse() {
            Ok(n) => n,
            Err(_) => return Err(String::from("25 should have parsed")),
        };

        if gauge(width) {
            Ok(())
        } else {
            Err(format!("{width}mm should have fitted the gauge"))
        }
    }

A body full of fallible steps reads far better with ? than with a stack of unwrap calls, and the Err value is printed in the failure report. The one restriction is that #[should_panic] cannot be combined with a Result-returning test, because the two disagree about what failure means.

Leaving a test out of the default run

    #[test]
    #[ignore = "sweeps a thousand widths; kept out of the default run"]
    fn full_sweep() {
        for mm in 1..=1000 {
            let expected = mm >= 10 && mm <= 40;

            assert_eq!(gauge(mm), expected, "at {mm}mm");
        }
    }

An ignored test is compiled, listed as ignored in the summary, and skipped. The string is optional and is shown in the output, which is the difference between a test somebody will run deliberately and a test everybody assumes is broken.

Where tests can live

LocationCan see private itemsCompiled into a release buildUsual purpose
#[cfg(test)] mod tests beside the codeYesNoUnit tests of internals
A file in tests/ at the crate rootNo, public API onlyNoIntegration tests
Examples inside /// doc commentsNo, public API onlyNoDocumentation that cannot go stale

Each file in tests/ is compiled as its own separate crate, which is why it sees your library exactly as an outside user would -- a useful discipline, and the reason an integration test cannot reach a private function no matter how it is written.


Real World Example: Seven Tests Find One Bug

A postage calculator has bands by weight and a doubled price for express. It is a dozen lines, it looks obviously right, and it contains a defect that no amount of reading it will reveal. Here it is with its tests, laid out as src/lib.rs with the line numbers that produces:

pub fn band(grams: u32) -> &'static str {
    if grams < 100 {
        "letter"
    } else if grams <= 750 {
        "small parcel"
    } else if grams <= 2000 {
        "medium parcel"
    } else {
        "large parcel"
    }
}

pub fn cost_pence(grams: u32, express: bool) -> u32 {
    if grams == 0 {
        panic!("a parcel must weigh something");
    }

    let base = match band(grams) {
        "letter" => 110,
        "small parcel" => 335,
        "medium parcel" => 590,
        _ => 1195,
    };

    if express {
        base * 2
    } else {
        base
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_light_item_is_a_letter() {
        assert_eq!(band(20), "letter");
    }

    #[test]
    fn the_letter_boundary_is_inclusive() {
        assert_eq!(band(100), "letter");
    }

    #[test]
    fn one_gram_over_the_letter_boundary_is_a_small_parcel() {
        assert_eq!(band(101), "small parcel");
    }

    #[test]
    fn the_top_band_has_no_ceiling() {
        assert_eq!(band(50_000), "large parcel");
    }

    #[test]
    fn express_doubles_the_base() {
        assert_eq!(cost_pence(500, true), cost_pence(500, false) * 2);
    }

    #[test]
    #[should_panic(expected = "must weigh something")]
    fn a_weightless_parcel_is_rejected() {
        cost_pence(0, false);
    }

    #[test]
    fn every_band_costs_more_than_the_one_below() -> Result<(), String> {
        let steps = [(50, 500), (500, 1500), (1500, 5000)];

        for (lighter, heavier) in steps {
            let low = cost_pence(lighter, false);
            let high = cost_pence(heavier, false);

            if low >= high {
                return Err(format!("{lighter}g at {low} is not cheaper than {heavier}g at {high}"));
            }
        }

        Ok(())
    }
}
cargo test

Output:

running 7 tests
test tests::a_light_item_is_a_letter ... ok
test tests::a_weightless_parcel_is_rejected ... ok
test tests::every_band_costs_more_than_the_one_below ... ok
test tests::express_doubles_the_base ... ok
test tests::one_gram_over_the_letter_boundary_is_a_small_parcel ... ok
test tests::the_top_band_has_no_ceiling ... ok
test tests::the_letter_boundary_is_inclusive ... FAILED

failures:

---- tests::the_letter_boundary_is_inclusive stdout ----
thread 'tests::the_letter_boundary_is_inclusive' panicked at src/lib.rs:43:9:
assertion `left == right` failed
  left: "small parcel"
 right: "letter"
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

failures:
    tests::the_letter_boundary_is_inclusive

test result: FAILED. 6 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

The tariff says a letter is anything up to and including 100 grams. The code says grams < 100, so a parcel weighing exactly 100 grams is charged 335 pence instead of 110. Change that one character to grams <= 100 and the suite goes green:

running 7 tests
test tests::a_light_item_is_a_letter ... ok
test tests::a_weightless_parcel_is_rejected ... ok
test tests::every_band_costs_more_than_the_one_below ... ok
test tests::express_doubles_the_base ... ok
test tests::one_gram_over_the_letter_boundary_is_a_small_parcel ... ok
test tests::the_letter_boundary_is_inclusive ... ok
test tests::the_top_band_has_no_ceiling ... ok

test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Look at which test caught it. band(20) passed with the bug in place and band(101) passed too, because both sit comfortably inside a band. Only the test that used the boundary value itself failed. This is the single most reliable rule in the whole subject: a range's interior tells you almost nothing, and the interesting values are the last one in, the first one out, zero, one, and the maximum.

The other tests are three different shapes of claim, and the shapes matter as much as the values. express_doubles_the_base asserts a relationship rather than a number, so it keeps working after a price rise that would have broken assert_eq!(cost_pence(500, true), 670). every_band_costs_more_than_the_one_below asserts a property across the whole table and returns Result so that its failure message can name which pair went wrong rather than just saying false. And a_weightless_parcel_is_rejected carries expected = "must weigh something", so it cannot be satisfied later by some unrelated panic wandering into cost_pence.

The #[cfg(test)] marker earns its keep here in a way that is easy to overlook. This test module is longer than the code it tests, and none of it reaches the shipped binary -- no size cost, no startup cost, nothing to strip. That is what makes it reasonable for tests to be verbose, repetitive and numerous, which are vices in ordinary code and virtues here. use super::*; is what gives them access; had these been integration tests in tests/, they could only have called the pub items, which is a useful constraint but a different one.

Now the honest part, because this code has two real design faults that the tests do not catch and could not. band returns &'static str and cost_pence then matches on that string, so a typo like "small parcell" would not be a compile error -- it would fall through to _ => 1195 and silently charge the most expensive rate. An enum would make that arm unnecessary and the typo impossible, and this is precisely the class of bug where tests are the wrong tool and the type system is the right one. The second fault is the panic! on a zero weight: a caller passing bad input deserves Module 5's Result, and the panic exists here only so that #[should_panic] has something to demonstrate. Beyond that, nothing tests the boundaries at 750 or 2000, nothing tests cost_pence(0, true), and base * 2 would overflow for an absurd base that this tariff cannot currently produce but a future one might.


Common Mistakes

  1. Testing the middle of a range instead of its edges. band(20) and band(101) both passed while the code was wrong. Every threshold needs the value at the boundary, the value one below and the value one above, and every numeric input needs zero and the maximum considered even if only to decide they are impossible.
  1. Bare #[should_panic]. It passes when the function panics for any reason whatsoever, so it survives the code being changed to panic somewhere completely different. Always give it expected = "..." with a distinctive fragment of the message.
  1. Forgetting use super::*;. The test module is a child module, not the same scope, so without that line every call fails to resolve. The error is clear but it appears the first time you write a test module and confuses everyone once.
  1. assert_eq! on a type with no Debug. The failure is a trait-bound error, not a failing test, and the fix is #[derive(Debug)] on the type. The same applies to PartialEq if the type cannot be compared at all.
  1. assert!(a == b) where assert_eq!(a, b) was meant. Both fail on the same inputs, but the first prints only the source text of the condition, so you learn that the values differed and not what either of them was. The second prints both.
  1. Test names that say nothing. test_band and works appear in the failure report and in nothing else, so a name that does not state the claim wastes the one line of documentation a failing test gets for free. Name it after what should be true.
  1. Asserting on something that varies between runs. HashMap iteration order, elapsed times, addresses, and anything involving the current date will pass locally and fail in CI at an inconvenient hour. Sort, freeze, or inject the varying part.
  1. Test-only helpers left outside the #[cfg(test)] module. A fixture builder written at file scope is compiled into the release binary and produces dead-code warnings there. Keep everything the tests alone need inside the module.
  1. Combining #[should_panic] with a Result-returning test. The two definitions of failure conflict and the compiler rejects it. Pick one: panic-based for validation that is genuinely meant to abort, Result for anything a caller could reasonably handle.

Best Practices

  • Name each test after the claim it makes, as a readable phrase: the_letter_boundary_is_inclusive tells a stranger what broke before they open the file.
  • Make one claim per test. Two assertions in one function means the second is never reached when the first fails, and the report tells you about half the damage.
  • Test boundaries at their exact values, plus one either side, and treat zero, one and the type's maximum as boundaries too.
  • Prefer assert_eq! and assert_ne! over assert! with a comparison, so failures print the values rather than the source text.
  • Assert relationships and properties as well as constants -- doubling, ordering, round-tripping -- because those survive changes that are supposed to be harmless.
  • Give #[should_panic] an expected fragment every time, and keep the fragment short enough to survive a reworded message but specific enough to identify the reason.
  • Return Result<(), E> from a test whose body has fallible steps, so ? can be used instead of a column of unwrap calls.
  • Remember what tests cannot do. A test checks the cases you thought of; a type checks every case. When a bug class can be made unrepresentable -- an enum instead of a string, a newtype instead of a bare integer -- do that first and test what is left.

Practice Exercises

  1. Add boundary tests for the other two thresholds: 750 and 751, 2000 and 2001. Establish whether the corrected band is right at both, and write down what the tariff would have to say for grams <= 750 to be the wrong comparison.
  1. Replace &'static str with enum Band { Letter, SmallParcel, MediumParcel, LargeParcel }, derive what assert_eq! needs, and rewrite cost_pence to match on it. List which test bodies had to change, which did not, and what happened to the _ => 1195 arm.
  1. Add an #[ignore]d test that sweeps every weight from 1 to 3000 grams and asserts that the cost never decreases as the weight increases. Run the default suite, confirm it is listed as ignored, then run it on its own and report what it found.
  1. Convert the zero-weight panic! into Result<u32, String>, then rewrite a_weightless_parcel_is_rejected without #[should_panic]. Compare the two versions and say in two sentences what the test can now check that it could not before.