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

import unit_threaded.asserts;
void funcThrows(string msg) { throw new Exception(msg); }
try {
    auto exception = funcThrows("foo bar").shouldThrow;
    assertEqual(exception.msg, "foo bar");
} catch(Exception e) {
    assert(false, "should not have thrown anything and threw: " ~ e.msg);
}
import unit_threaded.asserts;
void func() {}
try {
    func.shouldThrow;
    assert(false, "Should never get here");
} catch(Exception e)
    assertEqual(e.msg, "Expression did not throw");
import unit_threaded.asserts;
void funcAsserts() { assert(false); }
try {
    funcAsserts.shouldThrow;
    assert(false, "Should never get here");
} catch(Exception e)
    assertEqual(e.msg, "Expression threw core.exception.AssertError instead of the expected Exception");

Meta