throwsA function

Matcher throwsA(
  1. Object? matcher
)

This can be used to match three kinds of objects:

  • A Function that throws an exception when called. The function cannot take any arguments. If you want to test that a function expecting arguments throws, wrap it in another zero-argument function that calls the one you want to test.

  • A Future that completes with an exception. Note that this creates an asynchronous expectation. The call to expect() that includes this will return immediately and execution will continue. Later, when the future completes, the actual expectation will run.

  • A Function that returns a Future that completes with an exception.

In all three cases, when an exception is thrown, this will test that the exception object matches matcher. If matcher is not an instance of Matcher, it will implicitly be treated as equals(matcher).

Examples:

void functionThatThrows() => throw SomeException();

void functionWithArgument(bool shouldThrow) {
  if (shouldThrow) {
    throw SomeException();
  }
}

Future<void> asyncFunctionThatThrows() async => throw SomeException();

expect(functionThatThrows, throwsA(isA<SomeException>()));

expect(() => functionWithArgument(true), throwsA(isA<SomeException>()));

var future = asyncFunctionThatThrows();
await expectLater(future, throwsA(isA<SomeException>()));

await expectLater(
    asyncFunctionThatThrows, throwsA(isA<SomeException>()));

Implementation

Matcher throwsA(Object? matcher) => Throws(wrapMatcher(matcher));