How to check a function that raises an exception in Dart?

Let's say I have a function that throws an exception:

hello() {
    throw "exception of world";
}

I want to test it, so I am writing a test:

test("function hello should throw exception", () {
    expect(()=>hello(), throwsA("exception of world"));
});

You can see that I did not call hello()directly, I use instead ()=>hello().

This works, but I wonder if there is another way to write tests for it?

+3
source share
2 answers

You can pass hellodirectly by name instead of creating a closure that only calls hello.

This unit test passes:

main() {
  test("function hello should throw exception", () {
      expect(hello, throwsA(new isInstanceOf<String>()));
  });
}
+3
source

This article explains how to test exceptions https://www.dartlang.org/articles/dart-unit-tests/

+1
source

All Articles