shouldThrow

Verify that expr throws the templated Exception class. This succeeds if the expression throws a child class of the template parameter.

shouldThrow
(
T : Throwable = Exception
E
)
(
lazy E expr
,
in string file = __FILE__
,
in size_t line = __LINE__
)

Return Value

Type: auto

The caught throwable.

Throws

UnitTestException on failure (when expr does not throw the expected exception)

Examples

void funcThrows(string msg) {
    throw new Exception(msg);
}

try {
    auto exception = funcThrows("foo bar").shouldThrow;
    assert(exception.msg == "foo bar");
} catch (Exception e) {
    assert(false, "should not have thrown anything and threw: " ~ e.msg);
}
void func() {
}

try {
    func.shouldThrow;
    assert(false, "Should never get here");
} catch (Exception e)
    assert(e.msg == "Expression did not throw");
void funcAsserts() {
    assert(false, "Oh noes");
}

try {
    funcAsserts.shouldThrow;
    assert(false, "Should never get here");
} catch (Exception e)
    assert(
            e.msg
            == "Expression threw core.exception.AssertError instead of the expected Exception:\nOh noes");

Meta