Grzegorz
Grzegorz

Reputation: 95

Evaluate multiple asserts in unit test - not stop at the first failing one

Is it possible to ask rust to evaluate all asserts in a single unit test? Let's consider the following unit test.

#[test]
fn it_works() {
    assert_eq!(2 + 2, 5);
    assert_eq!(2 + 2, 4);
    assert_eq!(2 + 2, 6);
}

I would like to see that both the first and last asserts are failing. Right now, rust panics at the first one and stops evaluating remaining checks. The only solution that I came up with was to use panic::catch_unwind:

use std::panic;

#[test]
fn it_works2() {
    panic::catch_unwind(|| {
        assert_eq!(2 + 2, 5);
    });
    assert_eq!(2 + 2, 4);
    assert_eq!(2 + 2, 6);
}

Is there the more elegant way to do it?

I understand there are different opinion about multiple asserts in a single unit test but I do not intend to weigh in on any side of that discussion, just to know how to do it in rust.

Upvotes: 3

Views: 2240

Answers (1)

phimuemue
phimuemue

Reputation: 35983

I think I would write a separate test for each of them. Because usually you want all asserts to hold, and it does actually not matter very much if the first or the second failed - all of them must hold.

If this is not desirable, you could try to evaluate the conditions, and only have one single assert_eq that compares the resulting values as a tuple. You could then try to invent something that prints only differing elements.

To do that, you could do all the relevant comparisons one after another, and possibly store tuples (remembering left-hand and right-hand side) of failing comparisons in a Vec. At the end, you could assert that the Vec is empty. If it is not empty, you show the differences.

Upvotes: 1

Related Questions