6

I write some simple project in Dart (1.9.3) with unit tests using unittest library. I have a problem with checking if constructor throws an error. Here's the sample code I write for this issue purposes:

class MyAwesomeClass {
    String theKey;

    MyAwesomeClass();

    MyAwesomeClass.fromMap(Map someMap) {
        if (!someMap.containsKey('the_key')) {
            throw new Exception('Invalid object format');
        }

        theKey = someMap['the key'];
    }
}

and here are the unit tests:

test('when the object is in wrong format', () {
    Map objectMap = {};

    expect(new MyAwesomeClass.fromMap(objectMap), throws);
});

The problem is the test fails with following message:

Test failed: Caught Exception: Invalid object format

What do I do wrong? Is it a bug in unittest or should I test exceptions with try..catch and check if exception has been thrown?
Thanks for all!

Kuba T
  • 2,893
  • 4
  • 25
  • 30
  • Recommend reopening because it isn't immediately obvious from the "duplicate" topic how to apply it to constructors. – Suragch Oct 09 '19 at 13:56

1 Answers1

9

You can test if the Exception has been thrown using:

    test('when the object is in wrong format', () {
       Map objectMap = {};

       expect(() => new MyAwesomeClass.fromMap(objectMap), throws);
    });

passing as first argument an anonymous function raising the exception.

GioLaq
  • 2,489
  • 21
  • 26