Answer#
Generating tests is one of the tasks where an assistant saves typing, and where checking matters most: a test can pass and still test nothing. Ask for the cases you care about, run the result, and read it.
How to do it#
- Select the function in the editor (the selection is sent with its file name and line numbers) and press Write tests. The quick action sends: "Write thorough unit tests for this code." Or write your own request, naming the cases: "tests for 0, 100, below 0, above 100 and the extremes of i32".
- Apply or insert the test module into the file. This is the kind of result to expect:
/// Clamps a percentage to the range 0 to 100.
pub fn clamp_percent(value: i32) -> u8 {
value.clamp(0, 100) as u8
}
fn main() {
println!("{}", clamp_percent(140));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keeps_values_inside_the_range() {
assert_eq!(clamp_percent(0), 0);
assert_eq!(clamp_percent(55), 55);
assert_eq!(clamp_percent(100), 100);
}
#[test]
fn clamps_the_edges() {
assert_eq!(clamp_percent(-1), 0);
assert_eq!(clamp_percent(101), 100);
assert_eq!(clamp_percent(i32::MIN), 0);
assert_eq!(clamp_percent(i32::MAX), 100);
}
}- Run the tests. In Ruststudio use Run > Test: Run All Tests (Ctrl+Shift+T), or Test: Run Test at Cursor (F6). With a plain compiler the result looks like this:
running 2 tests
test tests::clamps_the_edges ... ok
test tests::keeps_values_inside_the_range ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; Check the tests themselves#
- Does each test have an assertion? A test that only calls the function passes unless it panics.
- Would it fail if the function were wrong? Change the function temporarily (use
min(100)only, drop the lower bound) and see which tests fail. If none does, the tests are too weak. - Are the edges there: empty input, zero, the largest and smallest values, invalid input?
- Do the expected values come from the specification, not from running the code and copying its output? The assistant cannot run your code, so it reasons from the source; where the source has a bug, the generated expectation may repeat it.
Common mistakes#
- Accepting tests that call private details and break at every refactor. Ask for tests of behaviour.
- Letting the assistant "fix" a failing test by changing the expected value. First decide whether the code or the test is wrong.
Related questions#
Can the assistant run the tests?#
No. It writes text; you run it with the commands above.