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 B

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

expressionMsg string

An optional expected message of the thrown exception.

message string

The error message to display.

file string

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

line size_t

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

Throws

DUnitAssertError if the assertation fails.

Examples

import core.exception : AssertError, RangeError;

class Foo : Exception
{
	this(string message)
	{
		super(message);
	}
}

class Bar
{
	public void baz()
	{
		throw new Foo("Thrown from baz.");
	}
}

auto bar = new Bar();
bar.baz().assertThrow();
bar.baz().assertThrow!(Foo)("Thrown from baz.");

delegate(){throw new Foo("Thrown from delegate.");}().assertThrow!(Exception)("Thrown from delegate.");

auto baz = [0, 1, 2];
baz[3].assertThrow!(RangeError)();

assert(false).assertThrow!(AssertError)("Assertion failure");

// Assert a DUnitAssertError is thrown if assertThrow fails.
null.assertThrow().assertThrow!(DUnitAssertError)("Failed asserting throw");

// Assert a DUnitAssertError is thrown if assertThrow fails due to mismatched error message.
baz[3].assertThrow!(RangeError)("Foo").assertThrow!(DUnitAssertError)("Failed asserting throw");

Meta