Let's say I have a Rust function named add that adds two numbers. I want to write a comprehensive set of unit tests to ensure it always works.
From what I know, there are two ways you can write the tests.
- Use
assert_eq!multiple times in one test function - Create many different functions—one for each set of inputs/outputs
Neither of these are ideal (see below). Is there another, better way to write unit tests in Rust?
Using multiple asserts
#[test]
fn test() {
assert_eq!(add(1, 2), 3);
assert_eq!(add(2, 4), 5);
assert_eq!(add(2, 3), 5);
}
This works well when everything passes. But if one assertion fails, you don't know which one. For instance, in the above test, the only help you get is "left: 6, right: 5". Which assertion caused this? It's fairly easy to tell because add is trivial, but in anything non-trivial, you have no idea.
Using multiple functions
#[test]
fn add_1_and_2() {
assert_eq!(add(1, 2), 3);
}
#[test]
fn add_2_and_4() {
assert_eq!(add(2, 4), 6);
}
This solves all the problems from using multiple assertions. However, the tests are becoming extremely verbose, and you need to create a unique function name for every single test. Imagine a function with 4-5 different parameters and you're testing all combinations. That's a lot of hard-to-name functions! But at least you'll know which assertion breaks.
JavaScript equivalent
Ideally, I'm looking for a solution with the same functionality as this JavaScript test using Jest.
const tests = [[1, 2, 3], [2, 4, 6]];
it.each(tests)("adding %s and %s gives %s", ([a, b, result]) => {
expect(add(a, b)).toBe(result);
})
If one of the tests fail, Jest will tell you exactly which one. And the actual test code is very concise and readable.