Rust
December 2, 2026 7 min read

Testing in Rust

HS
HEMANT SINGH
Technical Writer & Educator

1. What is Software Testing?

Software testing is the process of checking whether a program behaves as expected.

For example, suppose you create a function that adds two numbers.

fn add(a: i32, b: i32) -> i32 {
a + b
}

You expect:

add(10, 20) = 30

Testing allows you to verify this automatically.

Why is Testing Important?

  1. Finds bugs before users experience them.
  2. Helps maintain code quality.
  3. Makes it safer to modify existing code.
  4. Reduces manual testing work.
  5. Helps developers understand expected behavior.

2. Types of Testing in Rust

Rust supports different kinds of testing.


Type

Purpose

Unit Testing

Test individual functions or small code units

Integration Testing

Test how different parts of an application work together

Documentation Testing

Test code examples written in documentation

We will study all three.

3. Your First Unit Test

Rust provides a built-in testing framework.

Let's create a simple function and test it.

fn add(a: i32, b: i32) -> i32 {
a + b
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn test_add() {
assert_eq!(add(10, 20), 30);
}
}

Explanation

#[cfg(test)]

This tells Rust to compile the test module when running tests.

mod tests

Creates a module named tests.

use super::*

Imports items from the parent module so the tests can access them.

#[test]

Marks a function as a test function.

assert_eq!()

Checks whether two values are equal.

Run the Test

Open your terminal and execute:

cargo test

Expected Output

running 1 test
test tests::test_add ... ok

test result: ok. 1 passed; 0 failed

Your first Rust test is successful!

4. Understanding Assertion Macros

Rust provides several assertion macros for testing.

1. assert!

Checks whether a condition is true.

#[test]
fn test_condition() {
assert!(10 > 5);
}

If the condition is false, the test fails.

2. assert_eq!

Checks whether two values are equal.

#[test]
fn test_equal() {
assert_eq!(10 + 20, 30);
}

3. assert_ne!

Checks whether two values are not equal.

#[test]
fn test_not_equal() {
assert_ne!(10, 20);
}

Comparison


Macro

Purpose

assert!()

Checks a Boolean condition

assert_eq!()

Checks equality

assert_ne!()

Checks inequality

5. Test Multiple Functions

You can test multiple functions inside the same test module.

fn add(a: i32, b: i32) -> i32 {
a + b
}

fn subtract(a: i32, b: i32) -> i32 {
a - b
}

fn multiply(a: i32, b: i32) -> i32 {
a * b
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn test_add() {
assert_eq!(add(10, 5), 15);
}

#[test]
fn test_subtract() {
assert_eq!(subtract(10, 5), 5);
}

#[test]
fn test_multiply() {
assert_eq!(multiply(10, 5), 50);
}
}

Run:

cargo test

Expected result: three tests should pass.

6. Test Functions That Return Result

Rust tests can also return a Result.

This is useful when the code being tested can produce errors.

fn divide(a: f64, b: f64) -> Result<f64, String> {

if b == 0.0 {
return Err(String::from("Cannot divide by zero"));
}

Ok(a / b)
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn test_division() -> Result<(), String> {

let result = divide(10.0, 2.0)?;

assert_eq!(result, 5.0);

Ok(())
}
}

Here, ? returns an error from the test if the operation fails.

7. Test Expected Panics

Sometimes a function is expected to panic under certain conditions.

Rust provides the #[should_panic] attribute.

fn check_age(age: u32) {

if age < 18 {
panic!("Age must be 18 or above");
}
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
#[should_panic]
fn test_invalid_age() {
check_age(15);
}
}

This test passes because the function is expected to panic.

You can also check the panic message:

#[test]
#[should_panic(expected = "Age must be 18 or above")]
fn test_invalid_age() {
check_age(15);
}

8. Test Private Functions

Rust allows tests inside a module to access private functions through the parent module.

fn calculate_tax(amount: f64) -> f64 {
amount * 0.18
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn test_tax() {
assert_eq!(calculate_tax(1000.0), 180.0);
}
}

Even though calculate_tax() is private, the child test module can access it.

9. Integration Testing

Unit tests usually test small parts of your code.

Integration tests check whether different parts of your application work together through their public interfaces.

Cargo uses a special folder named tests for integration tests.

Project Structure

my_project/
│
├── Cargo.toml
│
├── src/
│ └── lib.rs
│
└── tests/
└── integration_test.rs

Step 1: Create a Library Function

Inside src/lib.rs:

pub fn add(a: i32, b: i32) -> i32 {
a + b
}

pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}

Step 2: Create an Integration Test

Create this file:

tests/integration_test.rs

use my_project::{add, multiply};

#[test]
fn test_add() {
assert_eq!(add(10, 20), 30);
}

#[test]
fn test_multiply() {
assert_eq!(multiply(10, 20), 200);
}

Replace my_project with the actual library crate name from your Cargo.toml, using underscores if the package name contains hyphens.

Step 3: Run Tests

cargo test

Cargo automatically discovers integration tests inside the tests directory.

10. Documentation Tests

Rust can also test code examples written in documentation comments.

These comments begin with ///.

/// Adds two numbers.
///
/// # Examples
///
/// ```
/// let result = my_project::add(10, 20);
/// assert_eq!(result, 30);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}

Cargo runs these documentation examples when you execute:

cargo test

The code examples in documentation are called documentation tests, or doctests.

11. Run Specific Tests

Cargo provides commands to control which tests run.


Command

Purpose

cargo test

Run all tests

cargo test test_add

Run tests matching test_add

cargo test --lib

Run library unit tests

cargo test --test integration_test

Run a specific integration test target

cargo test -- --nocapture

Show printed output from tests

cargo test -- --test-threads=1

Run tests using one test thread

Example

cargo test test_add

This runs tests whose names match test_add.

12. Test-Driven Development (TDD)

TDD stands for Test-Driven Development.

It is a development approach where you write tests before writing the actual implementation.

The basic process is:

  1. Write a test.
  2. Run the test and observe that it fails.
  3. Write the code.
  4. Run the test again.
  5. Improve the code while keeping the test passing.

Example

First, write a test:

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn test_square() {
assert_eq!(square(5), 25);
}
}

Then implement the function:

fn square(number: i32) -> i32 {
number * number
}

Now run:

cargo test

The test should pass.

13. Testing Best Practices

  1. Give tests meaningful names.
  2. Test normal inputs and edge cases.
  3. Test error conditions.
  4. Keep tests independent of one another.
  5. Avoid depending on a specific test execution order.
  6. Test public application behavior through integration tests.
  7. Run cargo test before committing important changes.
  8. Avoid relying on external services in ordinary unit tests.

14. Mini Project: Calculator with Tests

Let's create a calculator and test its operations.

Complete Code

fn add(a: f64, b: f64) -> f64 {
a + b
}

fn subtract(a: f64, b: f64) -> f64 {
a - b
}

fn multiply(a: f64, b: f64) -> f64 {
a * b
}

fn divide(a: f64, b: f64) -> Result<f64, String> {

if b == 0.0 {
return Err(String::from("Cannot divide by zero"));
}

Ok(a / b)
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn test_add() {
assert_eq!(add(10.0, 5.0), 15.0);
}

#[test]
fn test_subtract() {
assert_eq!(subtract(10.0, 5.0), 5.0);
}

#[test]
fn test_multiply() {
assert_eq!(multiply(10.0, 5.0), 50.0);
}

#[test]
fn test_divide() {
assert_eq!(divide(10.0, 2.0).unwrap(), 5.0);
}

#[test]
fn test_divide_by_zero() {
assert!(divide(10.0, 0.0).is_err());
}
}

fn main() {
println!("Addition: {}", add(10.0, 5.0));
println!("Subtraction: {}", subtract(10.0, 5.0));
println!("Multiplication: {}", multiply(10.0, 5.0));
}

Expected Test Result

running 5 tests
test tests::test_add ... ok
test tests::test_subtract ... ok
test tests::test_multiply ... ok
test tests::test_divide ... ok
test tests::test_divide_by_zero ... ok

test result: ok. 5 passed; 0 failed

15. Practice Exercises

Try these exercises:

  1. Create a function that checks whether a number is even.
  2. Write tests for even and odd numbers.
  3. Create a function that finds the maximum of two numbers.
  4. Write tests for positive, negative, and equal numbers.
  5. Create a function that calculates student grades.
  6. Test invalid marks and valid marks.
  7. Create a function that checks whether a student is eligible for admission.
  8. Write an integration test for a public function in your library.