Module test
Minimal unit test runner
When --cfg test
is provided as an argument to the compiler, this module will override
the main
entrypoint with the test runner which will run all the test cases defined in
the code that is being compiled.
Each test case is executed in a subprocess.
Example
fn add(x: i32, y: i32) -> i32 {
x + y
}
fn sub(x: i32, y: i32) -> i32 {
x - y
}
#[cfg(test)]
mod tests {
#[test]
fn test_add() {
assert_eq!(1.add(2), 3);
}
#[test]
fn test_sub() {
assert_eq!(1.sub(2), -1);
}
#[test]
fn test_panic() {
test::assert_panics!(panic!("oops"));
}
}
Run this example
Test attributes
The following attribute is supported: #[test::ignore]
to skip execution of a test (useful e.g. to make sure
that a test compiles but is not run). This can be used in combination with #[cfg_attr(...)]
to conditionally
enable a test only on certain configurations.
#[cfg_attr(not(target_arch = "x86_64"), test::ignore)]
fn test_is_x86_64() {
assert_eq!(cfg!(target_arch), "x86_64");
}
Run this example
Custom test frameworks
Nothing prevents you from writing your own framework, just compile with
--cfg custom_test_framework
. The TestCase and TEST_CASES constants are public and can be used to
implement custom test runners, or they can be discovered through reflection in a different way.
cases.
Modules
Structs
Functions
-
Test runner entrypoint.
Macros
Consts
-
List of all discovered test cases