Dart - 构造函数中异常的单元测试

Dart - Unit test for exception in constructor

我在 Dart (1.9.3) 中使用 unittest 库编写了一些带有单元测试的简单项目。我在检查构造函数是否抛出错误时遇到问题。这是我为此问题编写的示例代码:

class MyAwesomeClass {
    String theKey;

    MyAwesomeClass();

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

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

这是单元测试:

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

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

问题是测试失败并显示以下消息:

Test failed: Caught Exception: Invalid object format

我做错了什么?这是 unittest 中的错误还是我应该使用 try..catch 测试异常并检查是否已抛出异常?
谢谢大家!

您可以使用以下方法测试是否已抛出异常:

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

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

将引发异常的匿名函数作为第一个参数传递。