assertThrow

Assert that an expression throws an exception.

void
assertThrow
(
A : Throwable = Exception
B
)
(
lazy B expression
,
string expressionMsg = null
,
string message = "Failed asserting throw"
,
string file = __FILE__
,
size_t line = __LINE__
)

Parameters

expression
Type: B

The expression to evaluate in order to assert the exception is thrown.

expressionMsg
Type: string

An optional expected message of the thrown exception.

message
Type: string

The error message to display.

file
Type: string

The file name where the error occurred. The value is added automatically at the call site.

line
Type: size_t

The line where the error occurred. The value is added automatically at the call site.

Throws

DUnitAssertError if the assertation fails.

Examples

1 import core.exception : AssertError, RangeError;
2 
3 class Foo : Exception
4 {
5 	this(string message)
6 	{
7 		super(message);
8 	}
9 }
10 
11 class Bar
12 {
13 	public void baz()
14 	{
15 		throw new Foo("Thrown from baz.");
16 	}
17 }
18 
19 auto bar = new Bar();
20 bar.baz().assertThrow();
21 bar.baz().assertThrow!(Foo)("Thrown from baz.");
22 
23 delegate(){throw new Foo("Thrown from delegate.");}().assertThrow!(Exception)("Thrown from delegate.");
24 
25 auto baz = [0, 1, 2];
26 baz[3].assertThrow!(RangeError)();
27 
28 assert(false).assertThrow!(AssertError)("Assertion failure");
29 
30 // Assert a DUnitAssertError is thrown if assertThrow fails.
31 null.assertThrow().assertThrow!(DUnitAssertError)("Failed asserting throw");
32 
33 // Assert a DUnitAssertError is thrown if assertThrow fails due to mismatched error message.
34 baz[3].assertThrow!(RangeError)("Foo").assertThrow!(DUnitAssertError)("Failed asserting throw");

Meta