Unit tests
In general, a unit test is a function that instantiates a small portion of an application and verifies its behaviorĀ independently from other parts of the code base. In Rust, unit tests are usually written within a module. Ideally, they should only aim to cover the module's functionality and its interfaces.Ā
First unit test
The following is our very first unit test:
// first_unit_test.rs #[test] fn basic_test() { assert!(true); }
A unit test is written as a function and is marked with a #[test]
attribute. There's nothing complex in the precedingĀ basic_test
function. We have a basic assert!
call passing in true
. For better organization, you may also create a child module called tests (by convention) and put all related test code inside it.
Running tests
The way we run this test is by compiling our code in test mode. The compiler ignores the compilation of test annotated functions unless it's told to build in test mode. This can be achieved by passing theĀ --test
flag to rustc
when...