Module 13 · Testing, macros & unsafe
13.1Tests & doc tests
How Rust's built-in test runner replaces a test framework, where unit, integration and doc tests live, and which cargo test command runs what.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Test framework | Vitest or Jest, installed as a dev dependency | xUnit, NUnit or MSTest, in a separate test project | Built in: #[test] and cargo test |
| Marking a test | test("name", () => …) | [Fact] on a method | #[test] on a function |
| Checking a value | expect(actual).toEqual(expected) | Assert.Equal(expected, actual) | assert_eq!(actual, expected) |
| Expecting a failure | expect(() => f()).toThrow() | Assert.Throws<T>(() => F()) | #[should_panic] for a panic, assert!(result.is_err()) for an error |
| Where unit tests live | A separate *.test.ts file | A separate test project | A #[cfg(test)] mod tests at the bottom of the same file |
| Examples in docs that run | None built in | None built in | Doc tests: code blocks in /// comments |
In TypeScript, testing starts with a choice of framework: install Vitest or Jest, configure it, and write *.test.ts files.In C#, testing starts with a new project: dotnet new xunit (or NUnit, or MSTest), a reference to the code under test, and dotnet test to run it. Rust skips that step. The test runner is part of the compiler and Cargo: mark a function #[test], run cargo test, done. There’s nothing to install, and even the code examples in your documentation run as tests.
Your first test
Here’s a function that takes a percentage off a price, and a test for it.
With Vitest, the test goes in its own file and imports what it tests:
import { expect, test } from "vitest";
import { applyDiscount } from "./discount";
test("takes a quarter off", () => {
expect(applyDiscount(2000, 25)).toBe(1500);
});
With xUnit, the test goes in a separate test project that references the project under test:
using Xunit;
public class DiscountTests
{
[Fact]
public void TakesAQuarterOff()
{
Assert.Equal(1500, Pricing.ApplyDiscount(2000, 25));
}
}
In Rust, unit tests go in the same file as the code, in a module at the bottom:
pub fn apply_discount(price_cents: u32, percent: u32) -> u32 {
assert!(percent <= 100, "discount must be 0-100, got {percent}");
price_cents - cents_off(price_cents, percent)
}
fn cents_off(price_cents: u32, percent: u32) -> u32 {
price_cents * percent / 100
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn takes_a_quarter_off() {
assert_eq!(apply_discount(2000, 25), 1500);
}
#[test]
fn rounds_the_saving_down() {
assert_eq!(cents_off(999, 10), 99);
}
}Four pieces, each doing one job:
#[test]marks a function as a test, like callingtest()[Fact]. The#[...]syntax is an attribute. It looks like a decoratora C# attribute, but the compiler acts on it while compiling; nothing reads it at runtime. A test function takes no arguments, and it fails if it panics.mod tests { ... }is a module written inline, inside the file. The nametestsis only a convention.#[cfg(test)]means “compile this only when building tests”.cargo buildleaves the whole module out, so your release binary contains no test code.use super::*brings everything from the parent module into scope, private items included. That’s why the second test can callcents_off, which isn’tpub. A Vitest file can only import what a module exports.xUnit can only reachpublicmembers, orinternalones withInternalsVisibleTo; private methods are off-limits.
Run cargo test in the project folder:
$ cargo test
Compiling shop v0.1.0 (/home/ada/shop)
Finished `test` profile [unoptimized + debuginfo] target(s) in 2.03s
Running unittests src/lib.rs (target/debug/deps/shop-1baa0cfc48d29378)
running 2 tests
test tests::rounds_the_saving_down ... ok
test tests::takes_a_quarter_off ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests shop
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Each test is named by its module path, tests::takes_a_quarter_off. The Doc-tests section runs code examples from your documentation; there are none yet, and you’ll add one below.
Vitest has an opt-in version of this idea: in-source testing with import.meta.vitest, which you configure your production build to strip out. In Rust it’s the default way to write unit tests.
Assertions are macros
An assertion is ordinary code: if the check fails, it panics, and a panic fails the test. You can use the same macros outside tests, and they behave the same way. Here they are in a plain program:
The TypeScript version uses node:assert/strict, the assertion module built into Node, so it runs without a framework. In a Vitest file you’d write expect(...) instead.
C# has no assertion that throws outside a test framework: Debug.Assert is compiled out of Release builds, and a failed Trace.Assert ends the whole process. So the C# version below uses a three-line Check. In a test project, xUnit’s Assert.Equal and Assert.True play this part.
import assert from "node:assert/strict";
function applyDiscount(priceCents: number, percent: number): number {
if (percent < 0 || percent > 100) {
throw new RangeError(`discount must be 0-100, got ${percent}`);
}
return priceCents - Math.floor((priceCents * percent) / 100);
}
assert.equal(applyDiscount(2000, 25), 1500);
assert.notEqual(applyDiscount(2000, 10), 2000);
assert.ok(applyDiscount(999, 50) < 999, "a discount lowers the price");
console.log("All checks passed");Check(ApplyDiscount(2000, 25) == 1500, "25% off 2000");
Check(ApplyDiscount(2000, 10) != 2000, "10% changes the price");
Check(ApplyDiscount(999, 50) < 999, "a discount lowers the price");
Console.WriteLine("All checks passed");
static int ApplyDiscount(int priceCents, int percent)
{
ArgumentOutOfRangeException.ThrowIfNegative(percent);
ArgumentOutOfRangeException.ThrowIfGreaterThan(percent, 100);
return priceCents - priceCents * percent / 100;
}
static void Check(bool condition, string what)
{
if (!condition) throw new InvalidOperationException($"Check failed: {what}");
}fn apply_discount(price_cents: u32, percent: u32) -> u32 {
// A u32 can't be negative, so only the upper bound needs a check.
assert!(percent <= 100, "discount must be 0-100, got {percent}");
price_cents - price_cents * percent / 100
}
fn main() {
assert_eq!(apply_discount(2000, 25), 1500);
assert_ne!(apply_discount(2000, 10), 2000);
assert!(apply_discount(999, 50) < 999, "a discount lowers the price");
println!("All checks passed");
}Output
All checks passed
apply_discount uses assert! itself, to reject a bad percentage, much like throwing a RangeErrorThrowIfGreaterThan. That’s a normal use: assert! states something that must be true, in tests and in regular code. For an error the caller should handle, return a Result instead; Panics & custom errors covers the difference.
| Rust | Checks | Like |
|---|---|---|
assert!(condition) | The condition is true. | expect(condition).toBe(true)Assert.True(condition) |
assert_eq!(left, right) | The two values are equal, using ==. | expect(actual).toEqual(expected)Assert.Equal(expected, actual) |
assert_ne!(left, right) | The two values differ. | expect(actual).not.toEqual(expected)Assert.NotEqual(expected, actual) |
debug_assert!(condition) | Like assert!, but only in debug builds. | No direct equivalent.Debug.Assert(condition) |
Every one of them takes an optional message after the checked values, written like format!: assert_eq!(total, 1800, "total for {quantity} items"). On failure, assert_eq! prints both values, labeled left and right. It has no fixed “expected” side, unlike Assert.Equal, whose first argument is the expected value; many Rust projects put the actual value first.
assert_eq! compares with ==, so it compares contents: two Strings with the same text are equal, and so are two Vecs with the same elements, like toEqual, not toBe. For your own types, derive PartialEq (so == works) and Debug (so a failure can print the values):
#[derive(Debug, PartialEq)]
struct LineItem {
name: String,
cents: u32,
}
fn discounted(item: &LineItem, percent: u32) -> LineItem {
LineItem {
name: item.name.clone(),
cents: item.cents - item.cents * percent / 100,
}
}
fn main() {
let tea = LineItem {
name: String::from("tea"),
cents: 400,
};
let expected = LineItem {
name: String::from("tea"),
cents: 300,
};
assert_eq!(discounted(&tea, 25), expected);
println!("{:?}", discounted(&tea, 50));
}Output
LineItem { name: "tea", cents: 200 }#[derive(...)] asks the compiler to write those trait implementations for you; Macros & serde shows what it generates.
Panics, errors and ignored tests
A few more attributes and patterns cover most of what a test framework gives you. Here’s the discount code with a quantity parser added, and more tests:
use std::num::ParseIntError;
pub fn apply_discount(price_cents: u32, percent: u32) -> u32 {
assert!(percent <= 100, "discount must be 0-100, got {percent}");
price_cents - cents_off(price_cents, percent)
}
pub fn parse_quantity(text: &str) -> Result<u32, ParseIntError> {
text.trim().parse()
}
fn cents_off(price_cents: u32, percent: u32) -> u32 {
price_cents * percent / 100
}
#[cfg(test)]
mod tests {
use super::*;
// The two tests from "Your first test" go here too.
#[test]
fn discounts_from_a_table() {
let cases = [(2000, 0, 2000), (2000, 25, 1500), (999, 10, 900)];
for (price, percent, expected) in cases {
assert_eq!(
apply_discount(price, percent),
expected,
"{percent}% off {price}"
);
}
}
#[test]
#[should_panic(expected = "discount must be 0-100")]
fn rejects_more_than_100_percent() {
apply_discount(2000, 150);
}
#[test]
fn parses_a_padded_quantity() -> Result<(), ParseIntError> {
assert_eq!(parse_quantity(" 3 ")?, 3);
Ok(())
}
#[test]
fn rejects_a_word_as_quantity() {
assert!(parse_quantity("three").is_err());
}
#[test]
#[ignore = "slow: checks a million prices"]
fn never_raises_a_price() {
for price in 0..1_000_000 {
assert!(apply_discount(price, 10) <= price);
}
}
}- A table of cases. Rust has no built-in parameterized tests. Loop over an array of tuples instead, and put the inputs in the message, so a failure says which case broke.
#[should_panic(expected = "...")]passes only if the test panics with a message that contains that text.- A test can return
Result. Then?works inside it, and anErrfails the test, printing the error. Use this when the code under test returnsResult, instead of calling.unwrap()everywhere. - Expected errors are values. Most Rust functions report failure with
Result, not a panic, so most “this should fail” tests are a plain assertion:assert!(result.is_err()), orassert_eq!against the exactErr(...). #[ignore]skips a test unless you ask for it withcargo test -- --ignored. The reason after=is optional and shows up in the output.
| Vitest or Jest | Rust |
|---|---|
test.each([...])("...", (price, percent, expected) => ...) | A loop over an array of tuples, with the inputs in the assertion message. |
expect(() => applyDiscount(2000, 150)).toThrow("discount must") | #[should_panic(expected = "discount must")] |
expect(() => parseQuantity("three")).toThrow() | assert!(parse_quantity("three").is_err()): Rust returns the error instead of throwing it. |
An async test that awaits a promise that may reject | A test returning Result<(), E> that uses ?. |
test.skip("...", ...) | #[ignore = "reason"] |
test.only("...", ...) | No attribute: pass a name filter to cargo test. |
| xUnit | Rust |
|---|---|
[Theory] with [InlineData(2000, 25, 1500)] | A loop over an array of tuples, with the inputs in the assertion message. |
Assert.Throws<ArgumentOutOfRangeException>(() => ApplyDiscount(2000, 150)) | #[should_panic(expected = "discount must")] |
Assert.Throws<FormatException>(() => ParseQuantity("three")) | assert!(parse_quantity("three").is_err()): Rust returns the error instead of throwing it. |
| A test that calls methods that may throw | A test returning Result<(), E> that uses ?. |
[Fact(Skip = "reason")] | #[ignore = "reason"] |
Integration tests in tests/
Unit tests sit next to the code and can see its private parts. Integration tests use your crate the way another crate would: only its public API. Cargo treats every .rs file in a tests/ folder next to src/ as one:
shop/
├── Cargo.toml
├── src/
│ └── lib.rs the library, with its unit tests in mod tests
└── tests/
├── checkout.rs an integration test: built as its own crate
└── common/
└── mod.rs helpers shared by test files (not a test file itself)
An integration test file imports the library by its package name, and needs no #[cfg(test)], because Cargo compiles the tests/ folder only for cargo test:
use shop::{apply_discount, parse_quantity};
use std::num::ParseIntError;
#[test]
fn discounted_order_total() -> Result<(), ParseIntError> {
let quantity = parse_quantity("2")?;
assert_eq!(apply_discount(1000, 10) * quantity, 1800);
Ok(())
}Two rules follow from “each file is its own crate”:
- Only a library can be tested this way. A crate with just
src/main.rshas nothing to import. Put the logic insrc/lib.rsand keepmain.rsa thin wrapper that calls it; then both kinds of test can reach it. - Shared helpers go in
tests/common/mod.rs, and each test file that needs them addsmod common;. A file attests/common.rswould be treated as a test crate of its own and show up in the output asrunning 0 tests.
Doc tests: examples that run
A /// comment is documentation for the item below it, written in Markdown. cargo doc turns it into HTML pages, and cargo test compiles and runs every Rust code block in it:
/// Takes `percent` off a price in cents.
///
/// ```
/// use shop::apply_discount;
///
/// assert_eq!(apply_discount(2000, 25), 1500);
/// ```
///
/// # Panics
///
/// Panics if `percent` is over 100.
pub fn apply_discount(price_cents: u32, percent: u32) -> u32 {
assert!(percent <= 100, "discount must be 0-100, got {percent}");
price_cents - price_cents * percent / 100
}The example is the documentation readers see, and a test that fails as soon as the code stops matching it. JSDoc’s @exampleAn XML doc comment’s <example> is only text; nothing checks that it still compiles.
Each example is treated as a separate small program that uses your crate from outside, so it names the crate (use shop::apply_discount) and can only call public items. Fence options control what happens to an example:
| Fence | The example… |
|---|---|
``` | Compiles and runs, and must not panic. |
```should_panic | Compiles and runs, and must panic. |
```no_run | Compiles but doesn’t run: code that needs a network or a server. |
```compile_fail | Must fail to compile: shows what the API prevents. |
```ignore | Isn’t compiled. Use rarely. |
```text | Isn’t Rust: plain text such as sample output. |
A line that starts with # inside the example runs but isn’t shown in the HTML, so setup code doesn’t clutter the docs. (This site hides lines in its own Rust examples the same way.)
Running tests
cargo test builds and runs everything: unit tests, each integration test file, then doc tests. With the full shop crate:
$ cargo test
Compiling shop v0.1.0 (/home/ada/shop)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.57s
Running unittests src/lib.rs (target/debug/deps/shop-1baa0cfc48d29378)
running 7 tests
test tests::never_raises_a_price ... ignored, slow: checks a million prices
test tests::discounts_from_a_table ... ok
test tests::parses_a_padded_quantity ... ok
test tests::rejects_a_word_as_quantity ... ok
test tests::rounds_the_saving_down ... ok
test tests::takes_a_quarter_off ... ok
test tests::rejects_more_than_100_percent - should panic ... ok
test result: ok. 6 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/checkout.rs (target/debug/deps/checkout-6c978b0dd275feb3)
running 1 test
test discounted_order_total ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests shop
running 1 test
test src/lib.rs - apply_discount (line 5) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.61s
all doctests ran in 1.97s; merged doctests compilation took 0.72s
Each Running line is a separate executable, which is why integration tests can only use the public API. Tests in one executable run in parallel, one thread each, so they finish in whatever order they finish.
The flags you’ll use most:
cargo test # everything: unit, integration and doc tests
cargo test rejects # only tests whose name contains "rejects"
cargo test tests::takes_a_quarter_off -- --exact # exactly one test
cargo test --lib # unit tests only
cargo test --test checkout # one integration test file
cargo test --doc # doc tests only
cargo test -- --no-capture # show println! output as tests run (older spelling: --nocapture)
cargo test -- --ignored # run only the #[ignore] tests
cargo test -- --include-ignored # run all tests, ignored ones too
cargo test -- --test-threads=1 # one test at a time
As with cargo run, flags before -- go to Cargo and flags after it go to the test executable. A name filter is a plain substring match on the full test name, and every test executable applies it, so ones with no match report running 0 tests:
$ cargo test rejects
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.03s
Running unittests src/lib.rs (target/debug/deps/shop-1baa0cfc48d29378)
running 2 tests
test tests::rejects_a_word_as_quantity ... ok
test tests::rejects_more_than_100_percent - should panic ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 5 filtered out; finished in 0.00s
Running tests/checkout.rs (target/debug/deps/checkout-6c978b0dd275feb3)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
When a test fails
Change the first test in the two-test version from the start of this lesson to expect 1400, and cargo test reports:
running 2 tests
test tests::rounds_the_saving_down ... ok
test tests::takes_a_quarter_off ... FAILED
failures:
---- tests::takes_a_quarter_off stdout ----
thread 'tests::takes_a_quarter_off' (36444) panicked at src/lib.rs:16:9:
assertion `left == right` failed
left: 1500
right: 1400
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::takes_a_quarter_off
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
The panic message gives the file, line and column of the failed assertion, and both values. Other tests keep running: one failure doesn’t stop the rest. cargo test exits with a non-zero code, so CI fails the build.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
Unit test in #[cfg(test)] mod tests | Checking one function or type, including private helpers. The default. | Lives next to the code, sees private items, and is left out of normal builds. | #[test] fn name() { assert_eq!(...) } at the bottom of the file; cargo test --lib. |
Integration test in tests/ | Checking how public pieces work together, the way a user of your crate calls them. | Each file is a separate crate, so it can’t depend on private details. Refactoring inside the crate doesn’t break it. | tests/checkout.rs with use shop::...; and #[test] functions; cargo test --test checkout. |
Doc test in /// | Showing how to call a public function. | The example is documentation that can’t go stale: if it stops compiling or its assertions fail, cargo test fails. | A fenced block in a /// comment, using assert_eq! to show the result; cargo test --doc. |
#[should_panic(expected = "...")] | The code must panic: a broken precondition such as a percentage over 100. | Fails if nothing panics, or if the message doesn’t contain the text. | Always give expected, so an unrelated panic doesn’t count as a pass. |
A test returning Result | The code under test returns Result. | ? replaces .unwrap() calls, and an Err fails the test with the error printed. | fn name() -> Result<(), ParseIntError> { ...?; Ok(()) } |
#[ignore = "reason"] | A slow or environment-dependent test you don’t want on every run. | Keeps cargo test fast while the test stays compiled and runnable. | cargo test -- --ignored to run them, or --include-ignored in CI. |
Rule of thumb: write unit tests in a tests module for almost everything, add integration tests in tests/ for the public workflows, and put an example with an assertion in the docs of every public function. Run cargo test before every commit.
Is it an example that someone calling the function should read?
YesNoA doc test in the
///commentIt shows up in the generated docs and runs withcargo test. Libraries only.Does it use the crate only through its public API, the way another crate would, often across several modules?
YesNoAn integration test in
tests/Each file is its own crate. Shared helpers go intests/common/mod.rs.Otherwise: A unit test in
#[cfg(test)] mod tests, at the bottom of the file it tests. It can call private helpers too.
Under the hood
#[test] and #[cfg(test)] are instructions to the compiler. cargo test builds your library a second time with the --test flag, which does two things:
- It turns on
cfg(test), so thetestsmodules are compiled in. In a normal build they don’t exist: not even their names reach the binary. - It generates a
mainfunction, the test harness, that lists every#[test]function, applies your filter, and runs each test on its own thread, several at a time.
A test fails when its thread panics. The harness catches the panic, marks that test FAILED, and keeps going. Output written with println! is captured per test and shown only for failures, unless you pass --no-capture or --show-output.
Each file in tests/ is built the same way, as its own executable linked against the normal build of your library. Doc tests go through rustdoc: it pulls each example out of the comments, wraps it in a fn main if it doesn’t have one, and compiles it against your library as an outside crate. With edition 2024, it compiles the examples together into one program where it can, which is what the “merged doctests” line reports.
Mental model shiftNo framework, no runtime discovery
A test framework usually finds tests at runtime, by scanning files or by reflection over attributes. Rust’s test list is built by the compiler, so a misspelled attribute or a test that doesn’t compile is a build error, not a test that silently never runs.
Common pitfalls
Common pitfallComparing your own types needs two derives
assert_eq! uses == to compare and {:?} to print the values on failure. A struct without PartialEq can’t be compared at all:
struct LineItem {
name: String,
cents: u32,
}
fn main() {
let tea = LineItem {
name: String::from("tea"),
cents: 400,
};
let expected = LineItem {
name: String::from("tea"),
cents: 400,
};
assert_eq!(tea, expected);
}Rust doesn't compile this: error E0369
error[E0369]: binary operation `==` cannot be applied to type `LineItem`
--> main.rs:15:5
|
15 | assert_eq!(tea, expected);
| ^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| LineItem
| LineItem
|
note: an implementation of `PartialEq` might be missing for `LineItem`
--> main.rs:1:1
|
1 | struct LineItem {
| ^^^^^^^^^^^^^^^ must implement `PartialEq`
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider annotating `LineItem` with `#[derive(PartialEq)]`
|
1 + #[derive(PartialEq)]
2 | struct LineItem {
|
error[E0277]: `LineItem` doesn't implement `Debug`
--> main.rs:15:5
|
15 | assert_eq!(tea, expected);
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Debug` is not implemented for `LineItem`
|
= note: add `#[derive(Debug)]` to `LineItem` or manually `impl Debug for LineItem`
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider annotating `LineItem` with `#[derive(Debug)]`
|
1 + #[derive(Debug)]
2 | struct LineItem {
|
error[E0277]: `LineItem` doesn't implement `Debug`
--> main.rs:15:5
|
15 | assert_eq!(tea, expected);
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Debug` is not implemented for `LineItem`
|
= note: add `#[derive(Debug)]` to `LineItem` or manually `impl Debug for LineItem`
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider annotating `LineItem` with `#[derive(Debug)]`
|
1 + #[derive(Debug)]
2 | struct LineItem {
|Add #[derive(Debug, PartialEq)] to the struct. With only PartialEq, the error moves to the missing Debug.
Common pitfallWhere did my println! go?
The test harness captures output, and prints it only for tests that fail. To see output from passing tests, run cargo test -- --no-capture (printed as it happens; older guides spell it --nocapture, which still works) or cargo test -- --show-output (printed in a summary at the end).
Common pitfallTests run in parallel
Rust runs the tests in one executable on several threads at once. Tests that share something outside the process, such as a file, a port or an environment variable, can interfere with each other and fail at random. Give each test its own file name or port. As a quick check, cargo test -- --test-threads=1 runs them one at a time.
Common pitfallDoc tests need a library
Doc tests run only for a library crate (src/lib.rs). Examples in the docs of a binary-only crate are never compiled, so they can rot without anyone noticing. Moving the logic into lib.rs fixes this, and makes integration tests possible too.
Common pitfallshould_panic without expected passes on any panic
A bare #[should_panic] is satisfied by any panic: an index out of bounds or an .unwrap() on None in the code under test counts as a pass. Always add expected = "..." with part of the message you mean.
Try it yourself
Exercise: port this to Rust
Port parseRating to Rust as a function that returns a Result<u32, String> instead of throwing. Keep main printing the same three lines. Then add a #[cfg(test)] mod tests with three tests: a padded rating such as " 4 " parses to 4, "6" gives the exact out-of-range message, and "abc" is an error. Run them with cargo test.
function parseRating(text: string): number {
const trimmed = text.trim();
if (!/^\d+$/.test(trimmed)) {
throw new Error(`not a number: ${text}`);
}
const rating = Number(trimmed);
if (rating < 1 || rating > 5) {
throw new Error(`rating must be 1-5, got ${rating}`);
}
return rating;
}
for (const text of ["4", "6", "abc"]) {
try {
console.log(parseRating(text));
} catch (error) {
console.log((error as Error).message);
}
}foreach (var text in new[] { "4", "6", "abc" })
{
try
{
Console.WriteLine(ParseRating(text));
}
catch (FormatException error)
{
Console.WriteLine(error.Message);
}
}
static int ParseRating(string text)
{
if (!int.TryParse(text.Trim(), out var rating))
{
throw new FormatException($"not a number: {text}");
}
if (rating is < 1 or > 5)
{
throw new FormatException($"rating must be 1-5, got {rating}");
}
return rating;
}Expected output
4 rating must be 1-5, got 6 not a number: abc
Show a hint
Return Result<u32, String> instead of throwing: map_err turns the parse error into your message, and ? returns it early. In the tests module, compare whole results with assert_eq!, for example comparing the result for a padded 4 with Ok(4). Results of u32 and String already implement PartialEq and Debug.
Show a solution
fn parse_rating(text: &str) -> Result<u32, String> {
let rating: u32 = text
.trim()
.parse()
.map_err(|_| format!("not a number: {text}"))?;
if !(1..=5).contains(&rating) {
return Err(format!("rating must be 1-5, got {rating}"));
}
Ok(rating)
}
fn main() {
for text in ["4", "6", "abc"] {
match parse_rating(text) {
Ok(rating) => println!("{rating}"),
Err(message) => println!("{message}"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_a_padded_rating() {
assert_eq!(parse_rating(" 4 "), Ok(4));
}
#[test]
fn rejects_a_rating_out_of_range() {
assert_eq!(
parse_rating("6"),
Err(String::from("rating must be 1-5, got 6"))
);
}
#[test]
fn rejects_text() {
assert!(parse_rating("abc").is_err());
}
}parse_rating returns errors as values, so its tests are plain assertions: assert_eq! against Ok(4) and against the exact Err message, and assert! with is_err for text. No should_panic is needed, because nothing panics. The tests module compiles only for cargo test, and use super::* gives it access to parse_rating even though the function isn't pub.
Saved in this browser only.