Tainted\\Coders

Rust Testing

Last updated:

Running cargo test builds and runs all test binaries, only really caring about their exit code (e.g raised an error or not).

Test binaries are created from a package's [lib] and for each .rs file in tests/*.

To create a test all we have to do is annotate it with #[test].

#[test]
fn a_test() {
    assert_eq!(0, 0);
}

We can add setup code to our tests by annotating a module:

#[cfg(test)]
mod tests {

    fn setup_game() {
        // ...
    }

    #[test]
    fn movement_system_test() {
        // ...
    }
}

The compiler will only compile the code annotated with #[cfg(test)] when we run cargo test, not cargo run or cargo build.

#[cfg(...)] allows the compiler to conditionally compile code based on specific conditions. We should read it like "If this configuration exists, include this code".

With it we can target operating systems #[cfg(target_os = "android")] or specific features #[cfg(feature = "server")] or only in debug mode #[cfg(debug_assertions)]