codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🦀

Rust

42 / 58 topics
41Testing42Unit Tests43Integration Tests
Tutorials/Rust/Unit Tests
🦀Rust

Unit Tests

Updated 2026-05-15
10 min read

Unit Tests

Introduction

In software development, testing is a crucial step to ensure that your code behaves as expected. Rust provides a robust framework for writing unit tests directly within your source files using the #[cfg(test)] attribute and the #[test] macro. This tutorial will guide you through creating unit tests for individual functions in Rust.

Concept

Unit tests are focused on testing small, isolated pieces of code, typically individual functions or methods. They help verify that each component works correctly under various conditions. In Rust, you can write these tests within the same file as the code they're testing by using the #[cfg(test)] attribute to include them only when running tests.

Examples

Basic Unit Test

Let's start with a simple example. Suppose we have a function that adds two numbers:

Rust
1fn add(a: i32, b: i32) -> i32 {
2 a + b
3}

To test this function, we can write a unit test in the same file:

Rust
1#[cfg(test)]
2mod tests {
3 use super::*;
4
5 #[test]
6 fn test_add() {
7 assert_eq!(add(2, 3), 5);
8 assert_eq!(add(-1, 1), 0);
9 assert_eq!(add(-5, -5), -10);
10 }
11}

In this example:

  • We define a module tests with the #[cfg(test)] attribute to ensure it's only compiled when running tests.
  • We use use super::*; to bring all items from the parent module into scope.
  • The test_add function is marked with #[test], indicating that it's a test case.
  • We use assert_eq! to check if the output of add matches the expected result.

Running Tests

To run the tests, you can use the Cargo command-line tool:

Terminal
$ cargo test

This will compile your code and execute all tests. You should see an output similar to this:

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

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Testing for Panics

You can also write tests to ensure that your code panics under certain conditions:

Rust
1fn divide(a: i32, b: i32) -> i32 {
2 if b == 0 {
3 panic!("Division by zero");
4 }
5 a / b
6}
7
8#[cfg(test)]
9mod tests {
10 use super::*;
11
12 #[test]
13 fn test_divide() {
14 assert_eq!(divide(10, 2), 5);
15 assert_eq!(divide(-10, 2), -5);
16
17 // Test for panic
18 let result = std::panic::catch_unwind(|| divide(10, 0));
19 assert!(result.is_err());
20 }
21}

In this example:

  • The divide function panics if the divisor is zero.
  • We use std::panic::catch_unwind to test for a panic condition.

Testing with Setup and Teardown

Sometimes, you might need to set up some state before running tests and clean it up afterward. Rust provides the before_each and after_each hooks in the form of setup functions:

Rust
1struct Counter {
2 count: i32,
3}
4
5impl Counter {
6 fn new() -> Counter {
7 Counter { count: 0 }
8 }
9
10 fn increment(&mut self) {
11 self.count += 1;
12 }
13
14 fn get_count(&self) -> i32 {
15 self.count
16 }
17}
18
19#[cfg(test)]
20mod tests {
21 use super::*;
22
23 #[test]
24 fn test_counter() {
25 let mut counter = Counter::new();
26 assert_eq!(counter.get_count(), 0);
27
28 counter.increment();
29 assert_eq!(counter.get_count(), 1);
30 }
31}

In this example:

  • We define a Counter struct with methods to increment and get the count.
  • The test function creates an instance of Counter, increments it, and checks the count.

What's Next?

Now that you've learned how to write unit tests for individual functions in Rust, the next step is to explore integration tests. Integration tests focus on testing how different parts of your application work together. They are typically written in a separate directory and can test more complex scenarios involving multiple modules or even external dependencies.

Stay tuned for the next tutorial where we'll dive into writing integration tests!


PreviousTestingNext Integration Tests

Recommended Gear

TestingIntegration Tests