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");
}
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.
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.
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.
The easiest and shortest answer is:
expect(throws(), throwsException)
To test exception/error type:
expect(throws(), throwsA(predicate((e) => e is MyException)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With