Unit Tests
test attribute.
Unit Tests is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Testing in Rust
Rust has built-in testing — no external framework needed. Tests are ordinary functions annotated with #[test], run by cargo test.
Your First Test
A test function takes no arguments and uses assertions. If it returns normally, it passes; if it panics, it fails.
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[test]
fn it_adds() {
assert_eq!(add(2, 3), 5);
}
fn main() {
println!("{}", add(2, 3));
}Assertion Macros
The standard assertions are:
assert!(cond)— fails if condition is falseassert_eq!(a, b)— fails if not equalassert_ne!(a, b)— fails if equal
fn main() {
let x = 4;
assert!(x > 0);
assert_eq!(x, 4);
assert_ne!(x, 5);
println!("All assertions passed");
}The tests Module
By convention, unit tests live in a module annotated with #[cfg(test)] so they are compiled only during testing.
fn square(n: i32) -> i32 {
n * n
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn squares_correctly() {
assert_eq!(square(5), 25);
}
}
fn main() {
println!("{}", square(5));
}use super::*
Because the test module is nested, use super::* brings the parent module's items (the functions you want to test) into scope.
Running Tests
cargo test compiles and runs every test. It reports how many passed, failed, or were ignored.
cargo testTesting for Panics
Use #[should_panic] to assert that a function panics under certain conditions.
fn checked_div(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("division by zero");
}
a / b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "division by zero")]
fn panics_on_zero() {
checked_div(10, 0);
}
}
fn main() {}Tests Returning Result
A test can return Result, letting you use the ? operator. Returning Err fails the test.
fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse::<i32>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_number() -> Result<(), std::num::ParseIntError> {
let n = parse("42")?;
assert_eq!(n, 42);
Ok(())
}
}
fn main() {}Ignoring Tests
Mark slow or environment-specific tests with #[ignore]. Run them explicitly with cargo test -- --ignored.
#[test]
#[ignore]
fn expensive_test() {
// long-running work
}
fn main() {}Useful Test Flags
Helpful options when running tests:
cargo test name— run tests matching a namecargo test -- --nocapture— show println outputcargo test -- --test-threads=1— run serially
Testing Private Functions
Because the test module is nested inside the same file, it can reach private functions — something integration tests cannot do. This is a key advantage of unit tests.
fn internal(n: i32) -> i32 {
n + 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tests_private() {
assert_eq!(internal(4), 5);
}
}
fn main() {
println!("{}", internal(4));
}Quick Check
What attribute marks a function as a test that Cargo should run?
Recap
You learned Rust's built-in testing:
#[test]marks test functions- Assertions:
assert!,assert_eq!,assert_ne! - Tests live in a
#[cfg(test)]module withuse super::* #[should_panic]andResult-returning tests handle errorscargo testruns everything
Frequently asked questions
Is the “Unit Tests” lesson free?
Yes — the full text of “Unit Tests” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Unit Tests”?
test attribute. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Unit Tests” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Unit Tests
- Integration Tests
- Doc Comments
- Doc Tests