Learn/Testing & Debugging/Unit Testing

Unit Testing

Write unit tests for your Dart functions and classes

7 min~5 min read+40 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Test Case Selection Strategy
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Unit Testing

Unit tests verify individual functions and classes in complete isolation from the rest of your app. Each test focuses on a single piece of logic such as a calculation function, a model parser, or a validation method. Unit tests are the fastest type of test because they do not need a device, emulator, or any UI rendering. They catch bugs early in development and give you the confidence to refactor code knowing that if something breaks, a test will fail immediately. A well-tested Flutter app should have many unit tests covering all business logic, data transformations, and utility functions.

dart
1// test/calculator_test.dart
2import 'package:flutter_test/flutter_test.dart';
3
4// Class to test
5class Calculator {
6 int add(int a, int b) => a + b;
7 int divide(int a, int b) {
8 if (b == 0) throw ArgumentError('Cannot divide by zero');
9 return a ~/ b;
10 }
11}
12
13void main() {
14 late Calculator calculator;
15
16 // Runs before each test
17 setUp(() {
18 calculator = Calculator();
19 });
20
21 group('Calculator', () {
22 test('add returns sum of two numbers', () {
23 expect(calculator.add(2, 3), equals(5));
24 expect(calculator.add(-1, 1), equals(0));
25 expect(calculator.add(0, 0), equals(0));
26 });
27
28 test('divide returns integer division', () {
29 expect(calculator.divide(10, 3), equals(3));
30 expect(calculator.divide(9, 3), equals(3));
31 });
32
33 test('divide by zero throws ArgumentError', () {
34 expect(
35 () => calculator.divide(10, 0),
36 throwsA(isA<ArgumentError>()),
37 );
38 });
39 });
40}
41
42// Run: flutter test test/calculator_test.dart

Matchers

💡 Matchers

Common matchers include equals(x), isTrue, isFalse, isNull, isNotNull, isA<Type>(), contains(), greaterThan(x), lessThan(x), and throwsA(). You can combine them for expressive assertions like expect(value, allOf(isNotNull, greaterThan(5))).

Test Case Selection Strategy

Strong unit tests target behavior boundaries, not only happy paths:

  • Normal flow with representative valid input.
  • Edge values (empty, zero, max/min, special characters).
  • Failure paths and exception behavior.
  • Idempotency or repeat-call behavior when relevant.

If a function can fail silently in production, it needs an explicit test for that path.

Unit Test Robustness Checklist

  • Each test has one clear assertion objective.
  • Test names describe behavior, condition, and expected result.
  • Arrange, Act, Assert structure is consistent in the suite.
  • Exception tests verify both type and trigger condition.
  • Critical business rules are covered by both success and failure tests.

This Lesson In Simple Words

Write unit tests for your Dart functions and classes. Dart is the language behind Flutter, and clear Dart code makes your Flutter UI easier to maintain.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Prefer readable names, explicit intent, and async/await over deeply nested callbacks.

Deep Understanding Guide

Why this lesson matters

When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Treat each Dart concept as a building block for widgets, services, and tests you will write later.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Ignoring null safety and forcing values with ! without checking data flow.
  • Writing long functions that mix validation, transformation, and side effects together.
  • Using dynamic where a proper type would catch mistakes earlier.
  • Catching broad errors without keeping useful context for debugging.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write a small pure function and test it with edge cases.
  • Convert one callback-based snippet to async/await with proper error handling.
  • Refactor a long function into smaller helper methods with clear names.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does setUp() do in a test file?".

Quick Glossary

  • validation: Checks that confirm input is correct before processing.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Strong Dart habits lead to predictable APIs and cleaner boundaries between presentation and business logic.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Unit Testing" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Ignoring null safety and forcing values with ! without checking data flow.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does setUp() do in a test file?

setUp() runs before every individual test, ensuring each test starts with a fresh state.

How do you test that a function throws an exception?

Wrap the throwing call in a closure and use throwsA(isA<ExceptionType>()) matcher.

What command runs all tests in the test/ folder?

flutter test runs all tests in the test/ directory. You can also specify individual test files.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue