Testing Functions That Throw

When writing test expectations for functions that throw, we need a bit careful.

If we call the function directly, the test will fail as it won't catch the exception as we expect.

In these cases, we should always pass a closure when calling the expect method as shown here. 👇

Here's a comparison I made to explain why calling the method directly won't work.

These two implementations are equivalent. And they both fail because the function will execute and throw before expect() is even called. 👇

Hope this will save you some headaches. 👍

Want More?

Invest in yourself with my high-quality Flutter courses.

Flutter Foundations Course

Flutter Foundations Course

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a Flutter eCommerce app on iOS, Android, and web.

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

Learn about Firebase Auth, Cloud Firestore, Cloud Functions, Stripe payments, and much more by building a full-stack eCommerce app with Flutter & Firebase.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

Flutter Animations Masterclass

Flutter Animations Masterclass

Master Flutter animations and build a completely custom habit tracking application.