How Testing in Rust Is Built Into the Language. No Framework Needed.
I will be honest about my relationship with testing. Early in my career I treated it as something you do at the end if you have time. That approach cost me a lot of debugging hours and more than a few production incidents. The military taught me that you do not find out if your equipment works in the middle of an operation. You test it before.
Rust has testing built directly into the language and toolchain. There is no test framework to install, no configuration files to write, no separate test runner to learn. You write a function, add #[test] above it, and run cargo test. That simplicity removes every excuse for skipping tests.
1. Your First Test
Tests in Rust are functions annotated with #[test]. They live in the same files as the code they test, inside a mod tests block:
i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn test_add_negative() {
assert_eq!(add(-1, -1), -2);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn test_add_negative() {
assert_eq!(add(-1, -1), -2);
}
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn test_add_negative() {
assert_eq!(add(-1, -1), -2);
}
}
#[cfg(test)] tells the compiler to only include this module when running tests. It is excluded from the release binary. use super::* brings everything from the parent module into scope.
Run with cargo test. The output shows which tests passed and which failed.
In Python you use pytest which is a separate library. In Java you use JUnit, also a separate library with annotations and a test runner. In Rust it is all built in. The experience is noticeably cleaner.
2. The Assert Macros
Rust provides several assertion macros for different situations:
0, "expected positive, got {}", x);
assert_eq!(x, 42, "x should be 42 but was {}", x);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
#[test]
fn test_assertions() {
// assert basic truth
assert!(2 + 2 == 4);
// assert equality with better error messages
assert_eq!(2 + 2, 4);
assert_ne!(2 + 2, 5);
// custom error message
let x = 42;
assert!(x > 0, "expected positive, got {}", x);
assert_eq!(x, 42, "x should be 42 but was {}", x);
}
#[test]
fn test_assertions() {
// assert basic truth
assert!(2 + 2 == 4);
// assert equality with better error messages
assert_eq!(2 + 2, 4);
assert_ne!(2 + 2, 5);
// custom error message
let x = 42;
assert!(x > 0, "expected positive, got {}", x);
assert_eq!(x, 42, "x should be 42 but was {}", x);
}
The difference between assert! and assert_eq! is the error message. When assert_eq!(a, b) fails, it prints both values. When assert! fails, you only see “assertion failed.” Always prefer assert_eq! when comparing values.
3. Testing for Errors
For functions that return Result, testing that they fail correctly:
Result {
let age: i32 = s.parse().map_err(|_| format!("'{}' is not a number", s))?;
if age 150 {
return Err(format!("{} is not a valid age", age));
}
Ok(age as u8)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_age() {
assert_eq!(parse_age("25"), Ok(25));
}
#[test]
fn invalid_number() {
assert!(parse_age("abc").is_err());
}
#[test]
fn out_of_range() {
let result = parse_age("200");
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "200 is not a valid age");
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn parse_age(s: &str) -> Result<u8, String> {
let age: i32 = s.parse().map_err(|_| format!("'{}' is not a number", s))?;
if age < 0 || age > 150 {
return Err(format!("{} is not a valid age", age));
}
Ok(age as u8)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_age() {
assert_eq!(parse_age("25"), Ok(25));
}
#[test]
fn invalid_number() {
assert!(parse_age("abc").is_err());
}
#[test]
fn out_of_range() {
let result = parse_age("200");
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "200 is not a valid age");
}
}
fn parse_age(s: &str) -> Result<u8, String> {
let age: i32 = s.parse().map_err(|_| format!("'{}' is not a number", s))?;
if age < 0 || age > 150 {
return Err(format!("{} is not a valid age", age));
}
Ok(age as u8)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_age() {
assert_eq!(parse_age("25"), Ok(25));
}
#[test]
fn invalid_number() {
assert!(parse_age("abc").is_err());
}
#[test]
fn out_of_range() {
let result = parse_age("200");
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "200 is not a valid age");
}
}
For functions that should panic:
i32 {
if b == 0 {
panic!("division by zero");
}
a / b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "division by zero")]
fn test_divide_by_zero() {
divide(10, 0);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn divide(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 test_divide_by_zero() {
divide(10, 0);
}
}
fn divide(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 test_divide_by_zero() {
divide(10, 0);
}
}
#[should_panic] tells the test framework to expect a panic. The expected parameter checks that the panic message contains that string.
4. Tests Returning Result
Tests can return Result<(), E> which lets you use ? inside tests:
Result {
let content = fs::read_to_string("Cargo.toml")?;
assert!(content.contains("[package]"));
Ok(())
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::fs;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_file_read() -> Result<(), std::io::Error> {
let content = fs::read_to_string("Cargo.toml")?;
assert!(content.contains("[package]"));
Ok(())
}
}
use std::fs;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_file_read() -> Result<(), std::io::Error> {
let content = fs::read_to_string("Cargo.toml")?;
assert!(content.contains("[package]"));
Ok(())
}
}
If the ? propagates an error, the test fails with that error. This is cleaner than wrapping everything in .unwrap() inside tests.
5. Integration Tests
Unit tests live next to the code. Integration tests live in a separate tests/ directory at the project root and test the public API of your library crate:
my_project/
├── src/
│ └── lib.rs
└── tests/
└── integration_test.rs
// tests/integration_test.rs
use my_project::add; // uses the library's public API
#[test]
fn integration_add() {
assert_eq!(add(100, 200), 300);
}
my_project/
├── src/
│ └── lib.rs
└── tests/
└── integration_test.rs
// tests/integration_test.rs
use my_project::add; // uses the library's public API
#[test]
fn integration_add() {
assert_eq!(add(100, 200), 300);
}
Integration tests verify that the pieces of your library work together correctly from the outside. They are more expensive to run because they compile the entire library each time, but they catch interface bugs that unit tests miss.
In Java this distinction maps roughly to unit tests (testing individual classes) versus integration tests (testing through service boundaries). In Python pytest does not make a structural distinction but you would typically organize tests similarly by directory.
6. Organizing Tests and Running Subsets
As a project grows you will have many tests. Cargo gives you options:
cargo test # run all tests
cargo test test_add # run tests whose name contains "test_add"
cargo test --test integration_test # run only the integration test file
cargo test -- --ignored # run tests marked #[ignore]
cargo test -- --nocapture # show println! output during tests
cargo test # run all tests
cargo test test_add # run tests whose name contains "test_add"
cargo test --test integration_test # run only the integration test file
cargo test -- --ignored # run tests marked #[ignore]
cargo test -- --nocapture # show println! output during tests
Mark a test to skip by default with #[ignore]:
#[test]
#[ignore = "requires network access"]
fn test_live_api() {
// slow test that hits a real API
}
#[test]
#[ignore = "requires network access"]
fn test_live_api() {
// slow test that hits a real API
}
This test will not run with cargo test but will run with cargo test -- --ignored. Good for slow tests or tests with external dependencies.
7. Test Fixtures and Setup
Rust does not have built-in before/after hooks like JUnit’s @Before or pytest’s setup_function. You handle shared setup through helper functions or structs:
<button data-code="#[cfg(test)]
mod tests {
struct TestContext {
db: Vec,
}
impl TestContext {
fn new() -> Self {
// set up test data
TestContext {
db: vec![
String::from("alice"),
String::from("bob"),
String::from("carol"),
],
}
}
}
#[test]
fn test_find_user() {
let ctx = TestContext::new();
assert!(ctx.db.contains(&String::from("alice")));
}
#[test]
fn test_user_count() {
let ctx = TestContext::new();
assert_eq!(ctx.db.len(), 3);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
#[cfg(test)]
mod tests {
struct TestContext {
db: Vec<String>,
}
impl TestContext {
fn new() -> Self {
// set up test data
TestContext {
db: vec![
String::from("alice"),
String::from("bob"),
String::from("carol"),
],
}
}
}
#[test]
fn test_find_user() {
let ctx = TestContext::new();
assert!(ctx.db.contains(&String::from("alice")));
}
#[test]
fn test_user_count() {
let ctx = TestContext::new();
assert_eq!(ctx.db.len(), 3);
}
}
#[cfg(test)]
mod tests {
struct TestContext {
db: Vec<String>,
}
impl TestContext {
fn new() -> Self {
// set up test data
TestContext {
db: vec![
String::from("alice"),
String::from("bob"),
String::from("carol"),
],
}
}
}
#[test]
fn test_find_user() {
let ctx = TestContext::new();
assert!(ctx.db.contains(&String::from("alice")));
}
#[test]
fn test_user_count() {
let ctx = TestContext::new();
assert_eq!(ctx.db.len(), 3);
}
}
Each test creates its own TestContext. No shared state between tests, which means tests can run in parallel without interfering with each other. Cargo runs tests in parallel by default.
8. Doc Tests
This is one of my favourite features and something I had not seen before in other languages at this level of integration. You can write code examples in documentation comments and they are automatically compiled and run as tests:
i32 {
a + b
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let result = my_crate::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let result = my_crate::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
Run cargo test and the code in the documentation block is compiled and executed. If your example is wrong, the test fails. This means your documentation examples are always correct. The code serves as both documentation and a test at the same time.
In Python, doctest exists but is less integrated. Java has no equivalent. This feature alone has saved me from shipping documentation with broken examples more times than I can count.
9. Testing Async Code
For async functions you use #[tokio::test] instead of #[test]:
#[cfg(test)]
mod tests {
#[tokio::test]
async fn test_async_function() {
let result = some_async_function().await;
assert_eq!(result, expected_value);
}
}
#[cfg(test)]
mod tests {
#[tokio::test]
async fn test_async_function() {
let result = some_async_function().await;
assert_eq!(result, expected_value);
}
}
Add tokio with the full feature to dev-dependencies in Cargo.toml:
[dev-dependencies]
tokio = { version = "1", features = ["full"] }
[dev-dependencies]
tokio = { version = "1", features = ["full"] }
10. A Realistic Test Suite
Putting it all together with something close to a real scenario:
Result {
if name.len() 20 {
return Err(ValidationError::TooLong);
}
if !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Err(ValidationError::InvalidCharacters);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_username() {
assert!(validate_username("alice123").is_ok());
assert!(validate_username("user_name").is_ok());
}
#[test]
fn too_short() {
assert_eq!(validate_username("ab"), Err(ValidationError::TooShort));
}
#[test]
fn too_long() {
assert_eq!(
validate_username("this_username_is_way_too_long"),
Err(ValidationError::TooLong)
);
}
#[test]
fn invalid_characters() {
assert_eq!(
validate_username("user@name"),
Err(ValidationError::InvalidCharacters)
);
assert_eq!(
validate_username("user name"),
Err(ValidationError::InvalidCharacters)
);
}
#[test]
fn edge_cases() {
assert!(validate_username("abc").is_ok()); // exactly minimum
assert!(validate_username("a".repeat(20).as_str()).is_ok()); // exactly maximum
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// src/lib.rs
#[derive(Debug, PartialEq)]
pub enum ValidationError {
TooShort,
TooLong,
InvalidCharacters,
}
pub fn validate_username(name: &str) -> Result<(), ValidationError> {
if name.len() < 3 {
return Err(ValidationError::TooShort);
}
if name.len() > 20 {
return Err(ValidationError::TooLong);
}
if !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Err(ValidationError::InvalidCharacters);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_username() {
assert!(validate_username("alice123").is_ok());
assert!(validate_username("user_name").is_ok());
}
#[test]
fn too_short() {
assert_eq!(validate_username("ab"), Err(ValidationError::TooShort));
}
#[test]
fn too_long() {
assert_eq!(
validate_username("this_username_is_way_too_long"),
Err(ValidationError::TooLong)
);
}
#[test]
fn invalid_characters() {
assert_eq!(
validate_username("user@name"),
Err(ValidationError::InvalidCharacters)
);
assert_eq!(
validate_username("user name"),
Err(ValidationError::InvalidCharacters)
);
}
#[test]
fn edge_cases() {
assert!(validate_username("abc").is_ok()); // exactly minimum
assert!(validate_username("a".repeat(20).as_str()).is_ok()); // exactly maximum
}
}
// src/lib.rs
#[derive(Debug, PartialEq)]
pub enum ValidationError {
TooShort,
TooLong,
InvalidCharacters,
}
pub fn validate_username(name: &str) -> Result<(), ValidationError> {
if name.len() < 3 {
return Err(ValidationError::TooShort);
}
if name.len() > 20 {
return Err(ValidationError::TooLong);
}
if !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Err(ValidationError::InvalidCharacters);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn valid_username() {
assert!(validate_username("alice123").is_ok());
assert!(validate_username("user_name").is_ok());
}
#[test]
fn too_short() {
assert_eq!(validate_username("ab"), Err(ValidationError::TooShort));
}
#[test]
fn too_long() {
assert_eq!(
validate_username("this_username_is_way_too_long"),
Err(ValidationError::TooLong)
);
}
#[test]
fn invalid_characters() {
assert_eq!(
validate_username("user@name"),
Err(ValidationError::InvalidCharacters)
);
assert_eq!(
validate_username("user name"),
Err(ValidationError::InvalidCharacters)
);
}
#[test]
fn edge_cases() {
assert!(validate_username("abc").is_ok()); // exactly minimum
assert!(validate_username("a".repeat(20).as_str()).is_ok()); // exactly maximum
}
}
This covers the happy path, each error case, and the boundary conditions. A test like this takes a few minutes to write and saves you from every future refactor breaking the validation logic silently.
Summary
Testing in Rust is built into the language and toolchain. Unit tests live alongside code with #[test]. Integration tests live in tests/. Doc tests keep your documentation examples honest. cargo test runs everything. Tests can return Result and use ?. Async tests use #[tokio::test].
The friction to write a test in Rust is nearly zero. That is intentional and it changes how you think about writing tests as you go rather than as an afterthought.
What’s Next
The capstone project. Everything we have covered across fourteen articles comes together in one real, complete application. We will build a REST API with authentication, a database, structured logging, and proper error handling. The kind of thing you would actually build and deploy.
Happy coding and safe assembling!
Follow this series and join us in mastering Rust from scratch!

