Overview

11 Testing your Rust application

The chapter emphasizes that testing is not a one-size-fits-all process: the right mix of unit, integration, and workflow-level checks depends on the size of the application and the risks in the code. It stresses that Rust’s compiler can catch type and pattern issues, but it cannot verify business logic, expected error behavior, or whether an HTTP service returns the right response in real scenarios. The main takeaway is to focus testing effort on critical paths and especially on code that is complex, side-effect-heavy, or difficult to reason about.

It then walks through unit testing several pieces of business logic, starting with isolated functions such as pagination parsing and configuration loading from environment variables. The chapter shows how to write tests in the same file as the code using #[cfg(test)], #[test], and assertion macros, and how to handle error comparisons by relying on string formatting or trait support when necessary. It also highlights a common Rust testing challenge: tests run in parallel by default, so shared state like environment variables can interfere with other tests unless the code is made more side-effect free or the tests are structured carefully.

The chapter also covers more advanced scenarios where the code depends on external services or full request flow behavior. For a profanity-checking feature, it builds a mock server that mimics a third-party API and can be shut down remotely with a oneshot channel, allowing real HTTP calls to be tested without depending on the live service. It then moves on to Warp filter testing with the built-in test utilities, and finally to an integration-testing setup that restructures the project into a library plus binary, adds a separate test crate, resets a dedicated test database, and runs end-to-end-style HTTP checks for registration, login, and question creation. Along the way, the chapter uses the tests to improve the codebase itself, making it cleaner, more modular, and easier to maintain.

Unit testing focuses on isolated functions, whereas integration testing focuses on the interaction between modules and functions.
11-01
In these mocking strategies, we can call the library itself or the endpoint.
11-02
A oneshot channel to send exactly one message can be used to trigger a shutdown from the receiver side of the message.
11-03
Setting up the server and database before the integration test and tearing it down again
11-04
Restructuring our codebase to offer a library and a binary at the same time
11-05
Splitting main.rs into server.rs and lib.rs
11-06

Summary

  • Self-contained functions are well suited for unit tests, where we can feed the functions with different parameters and can always rely on side-effect free responses.
  • When trying to compare results, we need to implement the PartialEq trait on our structs.
  • Comparing errors is not always trivial, and the easiest solution is to compare the String the error produces (via the Display trait and the .to_string function).
  • Rust runs tests in parallel, which has side effects when testing different environment variables. This will impact all tests that rely on these environment variables and therefore need to be as self-contained as possible.
  • We don’t have to mock external API calls; we can change the URL they are calling to localhost and run a mock server on our own, where we control the response.
  • A mock server can be shut down via opening a channel between the test function and the server, where we can send over a signal that triggers a graceful shutdown of the server.
  • A oneshot channel is a great tool for communicating with a different part of the system (like a mock server) and triggering functions (like a shutdown) through messages.
  • Testing middleware is partly dependent on the web framework you are using. It is ideal if it allows testing routes without starting the server, like the warp::test module does.
  • Integration tests are large-scale tests that test functionality (partly) end to end in a local environment.
  • You can use your own folder or crate, or put them with the rest of your codebase.
  • You need to be able to start and stop the server and clean the database before and after each integration test run. This can be achieved through a bash file that starts a Docker environment, or through your own codebase via a oneshot channel and the Command module in the standard library.

FAQ

What are the main testing goals in this chapter?The chapter focuses on testing the most critical parts of a Rust web application: business logic, environment-dependent code, Warp filters, and full request flows. It emphasizes that you do not need 100% coverage everywhere, but you should thoroughly test the most important and most complex behavior.
What is the difference between unit testing and integration testing in this chapter?Unit tests check isolated functions with defined inputs and outputs, usually without side effects. Integration tests check how multiple parts of the application work together, such as request handling, database interaction, authentication, and returning the correct HTTP response.
How does Rust support unit testing out of the box?Rust provides the cargo test command, the #[test] attribute to mark test functions, and assertion macros like assert_eq! to compare expected and actual values.
Why is extract_pagination a good candidate for unit tests?extract_pagination is a self-contained function with no side effects. It only takes a HashMap as input and returns either a Pagination value or an Error, making it ideal for testing different input and error cases.
How do you test error cases when the error type cannot derive PartialEq?One approach used in the chapter is to implement Display for the error type and compare the string output instead. That way, the test can compare formatted error messages with assert_eq! even when the enum itself cannot derive PartialEq.
Why can environment variables cause problems in Rust tests?Rust runs tests in parallel by default, so one test that sets or removes environment variables can affect another test running at the same time. This can make tests flaky unless the environment is carefully controlled.
How did the chapter solve the environment-variable testing issue?The chapter removed environment setup from Config::new() and moved it into main(), then combined the config test cases into one test so that the missing-variable and set-variable scenarios happen sequentially in the same function.
What is the purpose of the mock server in the profanity tests?The mock server replaces the external API during tests. It returns predefined JSON responses so the real profanity-checking code can be tested without calling the live third-party service.
How does the mock server shut down after tests finish?It uses a Tokio oneshot channel. The test code sends a signal through the channel, and the server is started with Warp’s graceful shutdown support so it can stop cleanly.
Why did the chapter split the application into a library and a binary for integration testing?Splitting the codebase lets the integration-test crate import and use the application’s public functions, like setup_store and oneshot. It also keeps cargo run working through a small binary entry point while the reusable logic lives in the library.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rust Web Development Rust Web Development ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rust Web Development Rust Web Development ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rust Web Development Rust Web Development ebook for free