tezvyn:

Unit Testing in Dart: Verify Your Logic in Isolation

AI-drafted, machine-checkedSource: docs.flutter.devbeginner

A unit test is a microscope for your code. It checks a single function or class in isolation, ensuring it behaves correctly without worrying about the UI or network. Use it for business logic, not for testing rendered widgets or API calls.

WHY IT EXISTS To catch bugs early and cheaply. Running an entire app to check one small piece of logic is slow and inefficient. Unit tests provide a fast, automated way to verify that individual components work as expected before they are assembled into a larger system, giving you confidence to refactor and add features.

THE MENTAL MODEL A unit test is a conversation with a single piece of your code. You provide it with some input and ask, "Given this, do you produce the expected output?" It's about isolating a "unit"—a function, method, or class—from all its dependencies (like UI, database, or network) to test its internal logic exclusively.

HOW IT WORKS In Dart, you use the test package. You write test files (typically ending in _test.dart) that contain individual test() functions. Inside each test, you set up a scenario, call the code you want to test, and then use an expect() function to assert that the actual result matches the expected outcome. For example: expect(calculator.add(2, 2), 4);.

WHEN TO USE IT Use unit tests for pure logic. This includes data model classes, utility functions (like a date formatter), business logic in controllers or services, and algorithms. Anything that can be tested without rendering UI or making a network call is a prime candidate. They should be fast enough to run on every save.

WHEN NOT TO USE IT Do not use unit tests for things that require a running Flutter engine or external systems. For testing UI rendering and user interaction, use Widget Tests. For testing end-to-end flows that involve databases or APIs, use Integration Tests. A unit test that needs a network connection is not a unit test.

ONE CANONICAL EXAMPLE Imagine a simple Counter class that can increment and decrement. A unit test would first create an instance of Counter. Then, it would call the increment() method. Finally, it would use expect(counter.value, 1) to verify the state changed correctly. You'd write separate tests for decrementing, resetting, and handling edge cases like not going below zero.

Read the original → docs.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.