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

Kub*_*a T 4 unit-testing dart

我在 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'];
    }
}
Run Code Online (Sandbox Code Playgroud)

这是单元测试:

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

    expect(new MyAwesomeClass.fromMap(objectMap), throws);
});
Run Code Online (Sandbox Code Playgroud)

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

Test failed: Caught Exception: Invalid object format
Run Code Online (Sandbox Code Playgroud)

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

Joa*_*iba 6

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

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

       expect(() => new MyAwesomeClass.fromMap(objectMap), throws);
    });
Run Code Online (Sandbox Code Playgroud)

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