Sub topic 3
Assertions, Panics, and Rust Test Types
Assume you know basic Rust syntax, ownership, Result, and how to run cargo build and cargo run. Rust tests can check returned values, errors, and expected panics.
Assertions, Expected Panics, and `Result` Tests
Assertion macros compare an actual result with an expected result. Use assert! for a Boolean condition and assert_eq! or assert_ne! for values.
pub fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.parse()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_a_valid_port() -> Result<(), std::num::ParseIntError> {
assert_eq!(parse_port("8080")?, 8080);
Ok(())
}
#[test]
fn rejects_invalid_input() {
assert!(parse_port("no port").is_err());
}
#[test]
#[should_panic(expected = "index out of bounds")]
fn detects_an_expected_panic() {
let values = [1, 2, 3];
let _ = values[10];
}
}A test returning Result<(), E> passes when it returns Ok(()) and fails when it returns Err. This avoids calling unwrap and preserves the original error.
Use #[should_panic] only when a panic is the behavior being tested. The optional expected text makes the test stricter.
| Test mechanism | Best use |
|---|---|
| `assert_eq!` | Compare an actual value with an expected value |
| `assert!` | Check a condition |
| `#[should_panic]` | Confirm that invalid input triggers a panic |
| `Result<(), E>` | Propagate test setup or operation errors |
Integration Tests Against the Public API
Files in tests/ are separate crates. They can use only items exposed by the library crate, so they test the API that another package would see.
// tests/ports.rs
use my_geometry::parse_port;
#[test]
fn parses_port_through_public_api() {
assert_eq!(parse_port("443").unwrap(), 443);
}This test cannot access private functions or private modules. That boundary makes integration tests useful for checking public behavior.
Documentation Tests
Rust compiles examples in documentation comments when you run cargo test. These examples act as both tests and usage documentation.
/// Adds two numbers.
///
/// ```
/// assert_eq!(my_geometry::add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Running, Filtering, and Controlling Tests
cargo test
cargo test parses_port
cargo test --lib
cargo test --test ports
cargo test --doc
cargo test -- --nocapture
cargo test -- --ignoredThe first command runs all test kinds. The others select tests, show output, or run tests marked with #[ignore].
Exercise
Which test type should check a private parsing helper, and which should check the library's public parsing function?
Show answer
Use a unit test for the private helper and an integration test for the public function.