Loading Rust Test Generator...

How to Generate Rust Tests - Step by Step Guide

Note: The page writes the test scaffolding from your signatures; the cases themselves are yours to fill in. Functions it cannot turn into compiling code, such as ones that use an associated type like I::Item, are listed in a note instead of being guessed at.

Step 1

Paste your Rust code

Paste a whole .rs file or only the parts you care about. The page reads it the way the compiler sees the outline, so it knows about:

•
Functions and methods: free functions, methods taking &self, &mut self or self, and associated functions in impl blocks
•
Generics and lifetimes: trait bounds, where clauses, impl Trait arguments and const generics get a concrete type; lifetimes are left to the compiler
•
Modules and attributes: nested mod blocks are called by their path, #[cfg(…)] is copied onto the test, and existing tests are skipped

Example: Input Rust Function

A function that can fail:

pub fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        return Err("division by zero".to_string());
    }
    Ok(a / b)
}
Step 2

Check the generated module

Each test follows the layout the Rust book chapter on writing tests uses, with a case table added:

•
Typed tables: a Vec of tuples with the receiver, the arguments and the expected value
•
Results: Result returns use Some(value) for success and None for an error
•
Comparisons: assert_eq! only where the type implements PartialEq and Debug; otherwise the value is kept in _got with a TODO
•
Example rows: each table shows the shape of one case in a comment

Example: Generated Test Module

This is what the page writes for divide from Step 1:

// Paste this block at the end of the .rs file that holds the code above, then run `cargo test`.
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_divide() {
        // Each case: (a, b, expected)
        // expected is Some(value) when the call should return Ok(value), None when it should fail.
        let cases: Vec<(f64, f64, Option<f64>)> = vec![
            // TODO: add cases, for example:
            // (0.0, 0.0, Some(0.0)),
        ];
        for (a, b, expected) in cases {
            match (divide(a, b), expected) {
                (Ok(got), Some(want)) => assert_eq!(got, want),
                (Err(_), None) => {}
                (Ok(_), None) => panic!("expected an error, but divide returned Ok"),
                (Err(_), Some(_)) => panic!("expected Ok, but divide returned an error"),
            }
        }
    }
}

The table is empty on purpose: add your own rows, like the commented example, before you rely on the test.

Step 3

Copy or download and add cases

Put the module where cargo test will find it:

•
Copy: paste it at the end of the file that holds the functions
•
Download: saves the same text as tests.rs
•
Add cases: replace the commented example with real rows, including a receiver value for methods

Example: Running Your Tests

After adding the rows (6.0, 3.0, Some(2.0)), and (1.0, 0.0, None),, run:

$ cargo test
running 1 test
test tests::test_divide ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Want the source tidied first? The Rust formatter lays a file out with four-space indents and keeps every token as typed.

Frequently Asked Questions

What does a generated test look like?

Each function gets one #[test] with a table of cases: a Vec of tuples typed from the signature, holding the arguments and the expected result. A loop calls the function for every row and compares with assert_eq!. The table starts empty with one example row in a comment, so the module compiles and passes until you add real rows. All tests sit in a #[cfg(test)] mod tests block with use super::*.

How are Result and Option return values checked?

For a function that returns Result<T, E>, the expected column is an Option<T>: write Some(value) when the call should succeed with that value and None when it should return an error. A match then checks both sides, so the error type does not need PartialEq. For Result<(), E> or an Ok type that cannot be compared, the column is a bool that says whether the call should succeed. Option results are compared directly with assert_eq!.

Will the test module compile without changes?

For ordinary code it should; every pattern the page writes was compiled with rustc --test and run. Generic functions get a concrete type that fits their bounds (i32 for T: PartialOrd + Copy, String for impl AsRef<str>, a fn pointer for F: Fn(i32) -> i32, or one of your own types that implements your trait), lifetimes are left for the compiler to infer, unsafe calls are wrapped in unsafe { } and async functions run through a small block_on helper that uses only the standard library. Anything it cannot turn into code that compiles is left out and named in a note at the top instead.

How are methods tested?

Rust has no zero value for a struct, so the receiver is the first column of the table: you write the value to call the method on in each row, for example Counter::default() or Stack::<i32>::new(). Methods that take &mut self get a mut binding so the call works. Associated functions such as new are called as Type::new(…). Methods in impl Trait for Type blocks are not given tests; the note at the top lists them.

Which functions are left out, and why?

main is skipped because the program calls it, and functions that already have #[test] or sit under #[cfg(test)] are skipped too. A function is also left out when its signature uses an associated type such as I::Item, returns !, takes C variadic arguments, has a bound no known type satisfies, or is private inside a nested module where the tests module cannot reach it. Each one is named in a note. A result that does not implement PartialEq and Debug is still called, but bound to _got with a TODO instead of an assert_eq!.

Does it check my Rust code for mistakes?

Only the outline. It reads every item and signature, so an unclosed bracket or string, a missing comma between parameters, a parameter without a type or a statement outside a function is reported with the line and column. Function bodies are not type-checked, and nothing here runs your code, so build the crate with cargo check as well.

How do I run the tests?

Paste the block at the end of the .rs file that holds the functions, add a few rows to each table and run cargo test. If you would rather keep tests in their own file, save the inside of the module as tests.rs next to that file and declare it with #[cfg(test)] mod tests;. Rows left as comments are not run, so an untouched skeleton simply passes.

Is my code sent anywhere?

No. The tests are written by JavaScript in your browser tab. Your code is not uploaded to our server and nothing is kept, so a reload starts with an empty editor.