如何在 Dart 中测试抛出异常的函数?

Fre*_*ind 5 unit-testing dart

假设我有一个抛出异常的函数:

hello() {
    throw "exception of world";
}
Run Code Online (Sandbox Code Playgroud)

我想测试一下,所以我写了一个测试:

test("function hello should throw exception", () {
    expect(()=>hello(), throwsA("exception of world"));
});
Run Code Online (Sandbox Code Playgroud)

你可以看到我没有hello()直接调用,而是使用()=>hello().

它有效,但我想知道是否还有其他方法可以为其编写测试?

Gan*_*ede 6

您可以hello直接按名称传递,而不是创建仅调用的闭包hello

该单元测试通过:

main() {
  test("function hello should throw exception", () {
      expect(hello, throwsA(new isInstanceOf<String>()));
  });
}
Run Code Online (Sandbox Code Playgroud)