Explicitly testing for errors

How can I write a test case which provokes and checks for an error?

I’m trying something like this (found via Reddit), but get:

error: error union is ignored
    std.testing.expectError(MathError.NumberOfTheBeast, result);
const MathError = error {
    NumberOfTheBeast,
};


fn sum(a: i32, b: i32) !i32 {
    const result = a + b;

    if (result == 666) {
        return MathError.NumberOfTheBeast;
    } else {
        return result;
    }
}

test "Cannot sum to 666" {
    const result = sum(600, 66);
    std.testing.expectError(MathError.NumberOfTheBeast, result);
}

Ah, got it:

try std.testing.expectError(MathError.NumberOfTheBeast, result);

1 Like