How to Use the Command `cargo test` (with Examples)

How to Use the Command `cargo test` (with Examples)

The cargo test command is integral to any Rust developer’s toolkit, enabling the execution of unit and integration tests for Rust packages. This command offers various options to tailor the testing process to suit specific needs, such as filtering which tests to run, managing test concurrency, and running tests in release mode for optimized performance. By utilizing cargo test, developers can ensure code reliability and robustness through effective testing strategies.

Use Case 1: Only Run Tests Containing a Specific String in Their Names

Code:

cargo test testname

Motivation:

Sometimes, during development, it is crucial to focus on specific tests that are either failing or need isolation for targeted debugging. Running all tests can be time-consuming, especially as a codebase grows. In such cases, using the string filter feature provided by cargo test can significantly aid in streamlining the testing process, concentrating efforts on particular test scenarios by their name.

Explanation:

  • cargo test: This is the primary command used to execute tests within a Rust package.
  • testname: This argument acts as a filter, directing cargo test to execute only those tests whose names contain the specified string. It provides an easy way to focus on a subset of tests without the overhead of executing the entire test suite.

Example Output:

running 1 test
test tests::testname ... ok

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

Use Case 2: Set the Number of Simultaneous Running Test Cases

Code:

cargo test -- --test-threads 4

Motivation:

By default, cargo test executes tests concurrently to expedite the testing process. However, some environments may encounter resource constraints or necessity for specific testing conditions, such as sequential execution in a limited-resource development machine. Adjusting the number of test threads can help in balancing resource consumption and execution speed, ensuring tests run smoothly without overloading the system.

Explanation:

  • cargo test: Initiates the test run, executing tests prepared in the package.
  • --: This signifies the end of cargo options and the start of options specific to the test binary.
  • --test-threads 4: Sets the number of threads utilized for running tests concurrently to four, allowing controlled parallelism suited to the available system resources.

Example Output:

running 10 tests
test tests::test1 ... ok
test tests::test2 ... ok
...
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.10s

Use Case 3: Test Artifacts in Release Mode, with Optimizations

Code:

cargo test --release

Motivation:

There are scenarios where testing code optimized for performance is essential, particularly when assessing how the code will behave in production. By enabling the --release flag, tests simulate a production environment with all optimizations turned on, revealing any optimization-induced issues and validating the performance characteristics of the software.

Explanation:

  • cargo test: Targets all available tests to be run.
  • --release: Compiles the code with optimizations, akin to building the application for release, providing insights into the test’s performance impact and uncovering bugs not present in a debug build.

Example Output:

Finished release [optimized] target(s) in 0.35s
running 4 tests
test tests::test1 ... ok
...
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s

Use Case 4: Test All Packages in the Workspace

Code:

cargo test --workspace

Motivation:

In a workspace environment where multiple packages are developed concurrently, ensuring that changes in one package do not inadvertently break another is essential. Running tests across the entire workspace can maintain code integrity across related packages, promoting a seamless integration of changes throughout the project.

Explanation:

  • cargo test: Executes all defined test cases.
  • --workspace: Directs the command to test all packages within the current workspace, ensuring comprehensive testing coverage across related crates.

Example Output:

running 20 tests
test package1::tests::test1 ... ok
test package2::tests::test2 ... ok
...
test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.20s

Use Case 5: Run Tests for a Specific Package

Code:

cargo test --package package_name

Motivation:

When working within a larger workspace, there might be times when testing needs to be isolated to a single package—perhaps during a development sprint targeting specific functionality or when a single package has undergone changes. This focus prevents unnecessary workloads and tightly targets test execution.

Explanation:

  • cargo test: Executes the command to run tests.
  • --package package_name: Limits the test scope to a particular package within the workspace, identified by its unique package name.

Example Output:

running 5 tests
test package1::tests::test1 ... ok
...
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s

Use Case 6: Run Tests Without Hiding Output From Test Executions

Code:

cargo test -- --nocapture

Motivation:

Debugging test failures or gaining insights into test behavior often requires examining the output usually suppressed by default. By using the --nocapture option, all standard output and error messages during the test runs become visible, aiding in a more insightful debugging process.

Explanation:

  • cargo test: Executes available tests.
  • --nocapture: Ensures captured output from each test is displayed, allowing developers to see what would typically be hidden during normal test runs.

Example Output:

running 3 tests
test tests::example_test1 ... ok
Output from example_test1
test tests::example_test2 ... ok
Output from example_test2
...
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04s

Conclusion

The cargo test command is a comprehensive testing tool essential for Rust developers, enabling them to thoroughly verify and validate code functionality, performance, and integration across all facets of a Rust application. Whether focusing on specific tests, enhancing performance analysis, or illuminating the execution process, cargo test supports a range of valuable use cases that streamline the testing workflow. Through its flexibility and power, developers can ensure their Rust code is robust, efficient, and reliable.

Related Posts

How to Use the Command 'kopia' (with Examples)

How to Use the Command 'kopia' (with Examples)

Kopia is a fast, secure, and open-source backup tool designed to address the modern needs of data management.

Read More
How to use the command 'printenv' (with examples)

How to use the command 'printenv' (with examples)

The printenv command is a useful tool for interacting with environment variables in Unix-based systems.

Read More
How to use the command 'mas' (with examples)

How to use the command 'mas' (with examples)

The mas command-line interface is a powerful tool designed to work directly with the Mac App Store from your terminal or command line.

Read More