【问题标题】:Dart - Unit test for exception in constructor [duplicate]Dart - 构造函数中异常的单元测试[重复]
【发布时间】:2015-06-29 05:13:41
【问题描述】:

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

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 测试异常并检查是否引发了异常?
谢谢大家!

【问题讨论】:

  • 建议重新打开,因为从“重复”主题中无法立即看出如何将其应用于构造函数。

标签: unit-testing dart


【解决方案1】:

您可以使用以下方法测试是否引发了异常:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多