Basics of unit testing in Rust

I’m messing around with some Rust code at the moment, so expect a few posts in the near future. In this post I’ve going to jump straight into unit testing in Rust.

You don’t need to have a dependency on any unit testing frameworks as Rust has a unit testing framework integrated within it.

Our unit tests can sit along side our existing code using the conditional compilation annotation #[cfg(test)]. Let’s create a simple example test, which assumed we have a Stack implementation to test

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

    #[test]
    fn initial_state() {
        let s: Stack<i32> = Stack::new();
        assert_eq!(s.length, 0);
    }
}

The following line simply allows us to use code from the parent scope (i.e. allows us to use the Stack code).

use super::*;

Next up with have the #[test] annotation which (probably fairly obviously) declares the function initial_state to be a test function.

Ofcourse we need some form of assertation code, hence the assert_eq! macro.

We can also test whether our code panics by placed the #[should_panic] annotation after the #[test] annotation. This denotes that the system under test should panic (similar to exceptions in other languages).

Some times we need to ignore a test, in such cases we can use the #[ignore] annotation

Obviously we need run our tests, we can use cargo for this, simple run

cargo test

We can also run tests in parallel using the -test-threads option, for example if we want test to be run in parallel on two threads, we use

cargo test -- --test-threads=2

See further options around controlling how your tests are run controlling how your tests are run.