Book a free call

Testing and Debugging Rust Code: A Practical Guide

Rust gives you a test runner, a debugger and strict compiler checks in the box. Learn how to write tests, read compiler errors, and track down bugs step by step.

Hertiv engineering teamReviewed by a senior engineer
6 min read
Testing and Debugging Rust Code: A Practical Guide
On this page

Short answer

Testing Rust code means writing small checks with cargo test that run your functions and fail when the result is wrong. Debugging means finding why a check or a program fails, using the compiler's messages, the dbg! macro, and a debugger such as rust-gdb. The compiler catches many errors before the code runs, so tests focus on logic, not syntax.

What is testing in Rust?

Testing in Rust means writing small checks, called tests, that run your code and fail when the result is wrong. Rust ships a test runner with the language, so you write tests with the #[test] attribute and run them with cargo test, with no extra framework to install.

There are three kinds of test, and each one checks a different layer:

Test typeWhere it livesWhat it checks
Unit testIn the same file, under #[cfg(test)]One function or one small behaviour
Integration testIn the tests/ folderHow the public API works from outside
Doc testInside documentation commentsThat code examples in the docs actually run

Unit tests are the workhorse: they are fast, close to the code, and easy to run after every change. Integration tests catch problems at the boundary, such as a function that works alone but fails when called through the public interface. Doc tests are a bonus Rust gives you for free: every example in your docs is also a test.

How do you write tests in Rust?

You write tests in Rust by adding test functions to a module marked #[cfg(test)], each one annotated with #[test], and each one using assert! or assert_eq! to state what should be true.

  1. Pick the behaviour. Choose one thing the function should do, such as returning the right total for a known input.
  2. Write the test first or second. Either order works, but the test should exist before you call the code finished.
  3. Use plain values. Test with fixed inputs and expected outputs, so the test is deterministic and fast.
  4. Test the edges. Add cases for empty input, the largest value, and the error path, not just the happy path.
  5. Run them often. Run cargo test after every change, and run the full suite before every commit, so a regression is caught within minutes.
  6. Keep them fast. A slow suite is skipped. If a test needs a network or a database, mark it clearly and keep it out of the default run.

A good test reads like a specification: given this input, the function returns that output. If a test needs a long comment to explain what it checks, the function is probably doing too much. For the review side of this habit, see what a code review covers.

How does debugging work in Rust?

Debugging in Rust starts with the compiler, which catches many errors before the code runs and explains them in plain language. When the code compiles but behaves wrongly, you move to runtime tools: the dbg! macro, backtraces, and a debugger such as rust-gdb or rust-lldb.

The dbg! macro is the fastest first step. Wrap a value in dbg!(value) and Rust prints the file, the line number and the value to standard error, so you can see what the program actually computed at that point. It is quicker than a print statement because it also shows where it was called from.

For panics, set RUST_BACKTRACE=1 before running the program. The backtrace lists the function calls that led to the panic, which usually points at the line where an assumption broke. A debugger goes further: you can set a breakpoint, step through the code line by line, and inspect variables as they change.

The compiler's borrow checker deserves a mention here. Many new Rust developers fight it, but it is really a debugging tool that runs early: it finds data races and use-after-free bugs at compile time, so you never have to chase them in production. Read its messages carefully, because they usually name the exact fix.

Example (hypothetical): a test suite that runs in minutes, not hours

Example (hypothetical): a small team maintains a Rust service with 150 unit tests and 24 integration tests. Each unit test takes about 0.4 seconds, so the unit suite takes 150 times 0.4, which is 60 seconds. Each integration test takes about 5 seconds, so that suite takes 24 times 5, which is 120 seconds.

The whole suite therefore takes 60 plus 120, which is 180 seconds, or 3 minutes. The team runs the unit tests on every save and the full suite before every commit, so a broken change is found within minutes of being written.

Later the suite grows to 600 unit tests, which would take 600 times 0.4, or 240 seconds. The team splits the run across 4 parallel jobs, so the wall-clock time is 240 divided by 4, which is 60 seconds again.

The numbers are invented to show the arithmetic, not a real project. The point is that a test suite stays useful only if it stays fast, and parallel runs are the usual way to keep it fast as it grows.

What are the common mistakes?

The most common mistakes in Rust testing are testing only the happy path, writing tests that depend on order or on shared state, and ignoring compiler warnings that point at real bugs.

  • Only happy-path tests. A function that works for normal input and panics on empty input will fail in production. Test the edges.
  • Tests that share state. Tests run in parallel by default, so a test that writes to a shared file can fail when another test runs at the same time. Keep tests independent.
  • Ignoring warnings. Compiler warnings about unused variables or dead code often mark logic that is not doing what you think. Treat them as bugs until proven otherwise.
  • Testing through the network. A test that calls a live service is slow and flaky. Replace the service with a small fake in tests.
  • No test for the fix. When you fix a bug, add a test that fails without the fix. Without it, the bug can come back silently.

The last point is the one teams skip most often, because the fix feels done once the bug is gone. A regression test is what keeps it gone.

How do you test async Rust code?

You test async Rust code by running it inside an async runtime in the test, most often with the #[tokio::test] attribute, so the test function can use .await just like production code.

Async tests need the same discipline as sync tests, plus two extra habits. First, keep the async work small: test the logic in a plain function where possible, and use the async test only to check that the pieces connect. Second, control time. A test that waits for a real timeout is slow and flaky, so inject a fake clock or a short timeout in tests.

For code that talks to a network or a database, replace the real connection with a fake that returns fixed data. The test then checks your logic, not the network. If the fake and the real service disagree, that is a different test, one that runs against a real service on a schedule, not on every commit.

What tools help beyond cargo test?

Beyond cargo test, the tools most Rust teams use are cargo clippy for linting, cargo fmt for formatting, and cargo nextest for a faster, clearer test runner.

Clippy checks for common mistakes and awkward patterns, such as a loop that could be an iterator, and it often catches bugs that tests miss. Run it in continuous integration, because a warning that nobody sees is the same as no warning. cargo fmt keeps the code formatted the same way everywhere, which makes reviews faster and diffs smaller.

Nextest runs each test in its own process and reports failures more clearly than the built-in runner, which helps when a suite grows large.

For code that must handle many inputs, property-based testing with a library such as proptest generates random cases and finds the edge cases a human would not think of. Together these tools turn testing from a chore into a habit, and they fit naturally into a pipeline that builds and tests on every change, as described in what CI/CD does.

If you are building a product around this kind of engineering, custom software development teams usually set the same checks up from day one.

Key takeaways

  • Rust ships a test runner, so cargo test needs no extra framework
  • Unit, integration and doc tests check different layers of the code
  • The dbg! macro and backtraces find most runtime bugs fast
  • Keep the suite fast and independent, or it will be skipped
  • Clippy, formatting and property tests catch what unit tests miss

Frequently asked questions

Do I need a testing framework for Rust?

No. Rust ships a test runner with the language, so cargo test runs tests written with the #[test] attribute. Third-party runners such as cargo nextest add speed and clearer output, but they are optional, not required.

What is the difference between a unit test and an integration test?

A unit test lives in the same file as the code and checks one function or one small behaviour. An integration test lives in the tests folder and checks the public API from outside, the way a user of the library would call it.

How do I debug a Rust panic?

Run the program with RUST_BACKTRACE=1 set, which prints the function calls that led to the panic. Read the top of the trace first, since it usually names the line where an assumption broke. Then add a dbg! call or a breakpoint at that line.

Why does the Rust compiler reject my code?

Most often it is the borrow checker, which stops two parts of the code from using the same data in conflicting ways. Read the error message fully: it usually explains the conflict and suggests a fix, such as borrowing instead of moving a value.

Can I test async Rust code with cargo test?

Yes, by using an async test attribute such as #[tokio::test], which runs the test inside the Tokio runtime so you can use .await. Keep the async part small and test the logic in plain functions where you can.

How many tests should a Rust project have?

Enough to cover the behaviour that matters, including edge cases and error paths, and few enough that the suite stays fast. A good sign is that every bug fix adds a test that fails without the fix. Count coverage of behaviour, not lines.

Found this useful? Share it.
Hertiv engineering team

Written from projects we build for clients: software products in production. Every post is reviewed by a senior engineer before publishing and updated when practice changes.

About HertivHow we work

Building in Rust and want the engineering done right? Talk to Hertiv.

A senior engineer replies within one business day. Or see our Custom Software Development service.

Book a free call

Keep reading

All posts

Tell us what you want to build

A senior engineer reads every request and replies within one business day with questions, a rough range, or a call link.

  • NDA on request before any details
  • You own all code, models and IP
  • US, UK and EU time-zone overlap

Your email app should open with your message ready to send. If it does not, write to [email protected].

Prefer email? Write to [email protected]
Estimate costBook a call