Unit test
- Rust course
- Intermediate
- Lesson 83/115
- 4 min
Write unit tests with #[test].
Unit tests
Writing tests in Rust needs no extra tools. Functions marked with #[test] are run by cargo test; a test that panics counts as failed. Unit tests live in a tests module in the same file as the code they test:
fn topla(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iki_sayiyi_toplar() {
assert_eq!(topla(2, 3), 5);
}
}Thanks to use super::*;, tests can also reach private functions.
Test output
cargo test prints each test's result and a summary:
running 2 tests
test tests::iki_sayiyi_toplar ... ok
test tests::negatifleri_toplar ... FAILED
failures:
---- tests::negatifleri_toplar stdout ----
assertion `left == right` failed
left: -1
right: 1
test result: FAILED. 1 passed; 1 failedThe println! output of passing tests is hidden by default; to see it, use cargo test -- --nocapture. #[ignore] excludes slow tests from the default run.
Practice First test
Write fn topla(a: i32, b: i32) -> i32 and a #[cfg(test)] mod tests containing a #[test] checking it with assert_eq!. Since the exercise environment runs main, print the result of topla(2, 3) in main.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn topla(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", topla(2, 3));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iki_sayiyi_toplar() {
assert_eq!(topla(2, 3), 5);
}
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>cargo test topla</code> run?
- None
- Tests whose name contains "topla" Correct answer
- The topla function
- All tests
Explanation: The argument is a filter. To run one test by its full name, use cargo test tests::iki_sayiyi_toplar -- --exact.
2 Test marker
#[cfg(test)]
mod tests {
use super::*;
#[____]
fn iki_sayiyi_toplar() {
assert_eq!(topla(2, 3), 5);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iki_sayiyi_toplar() {
assert_eq!(topla(2, 3), 5);
}
}
Explanation: #[test] registers the function with the test runner.
3 Command and effect
| Term | Meaning |
|---|---|
cargo test |
All tests |
cargo test topla |
Filters by name |
cargo test -- --nocapture |
Shows output |
#[ignore] |
Skipped by default |