How do I test for an exception in Dart | Flutter?

How do I test for an exception in Dart | Flutter?

Using matchers to test for exceptions in Dart | Flutter

How to test for Custom Exceptions in dart?

Say you have written a code that throws a custom exception and you created it.

Let's call it

 NotInitializedException

Now how do you test for this exception while writing unit tests in dart?

No sweat!

You can use TypeMatcher<T> class

TypeMatcher is a Matcher subclass that supports validating the Type of the target object.

Let's see an example:-

class MockUser {
  var _isInitialized = false;
  bool get isInitialized => _isInitialized;

void testInitialize() {
    if (!isInitialized) throw NotInitializedException();
  }
}

Here's how you would write a test for this

void main() {
  group('Mock User', () {
      final user = MockUser();
      test('Test that initialization throws the right exception', () {
          final result = user.testInitialized()
          expect(result, throwsA(const TypeMatcher<NotInitializedException>()));
    });
}

throwsA

The throwsA matcher can be used to test 3 kinds of objects:

  1. A function that throws an exception when called, like in our case.
  2. A future that completes with an exception
  3. A function that returns a future that completes with an exception.

That's all.