Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test an exception from a future

Continuing from yesterday question, how would I test that a async method throws an exception.

main(){
  test( "test2", () async {
    expect( await throws(), throwsException);
  });

}

Future throws () async {
  throw new FormatException("hello");
}
like image 379
richard Avatar asked Jul 22 '15 09:07

richard


People also ask

How do you use the Future in darts?

A future (lower case “f”) is an instance of the Future (capitalized “F”) class. A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed. Note: Uncompleted is a Dart term referring to the state of a future before it has produced a value.

How do you catch an exception in darts?

The try / on / catch Blocks The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch.

What is then () in Flutter?

In simple words: await is meant to interrupt the process flow until the async method has finished. then however does not interrupt the process flow (meaning the next instructions will be executed) but enables you to run code when the async method is finished.


1 Answers

The easiest and shortest answer is:

expect(throws(), throwsException)

To test exception/error type:

expect(throws(), throwsA(predicate((e) => e is MyException)));
like image 189
Andrey Gordeev Avatar answered Oct 06 '22 03:10

Andrey Gordeev