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
,
string file = __FILE__
,
size_t line = __LINE__
)

Return Value

Type: auto

A ThrownInfo containing info about the throwable

Throws

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

Examples

void funcThrows(string msg) { throw new Exception(msg); }
try {
    auto exceptionInfo = funcThrows("foo bar").shouldThrow;
    assert(exceptionInfo.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