FlutterAdvanced 2 min read

Flutter unit tests for domain behavior

Write focused unit tests with representative inputs, edge cases and a clear expected result.

On this page

A unit test verifies a small behavior without starting a complete application. Functions, parsers and feature-state transitions are often good boundaries. A useful test should fail when the behavior users rely on is broken.

Start with an observable contract

The function below converts completed and total counts to a bounded percentage. This example lives in a local test file and runs with flutter test. It is intentionally not a DartPad app.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

import 'package:flutter_test/flutter_test.dart';

int progressPercent(int completed, int total) {
  if (total <= 0) return 0;
  return ((completed / total) * 100).round().clamp(0, 100).toInt();
}

void main() {
  test('reports meaningful progress and bounds invalid counts', () {
    expect(progressPercent(1, 4), 25);
    expect(progressPercent(0, 0), 0);
    expect(progressPercent(8, 4), 100);
    expect(progressPercent(-1, 4), 0);
  });
}

Read the result

The assertions describe product behavior, including a deliberate policy for zero total items. In a real project, import the implementation from lib rather than duplicating it inside the test.

Make the expected behavior independent of implementation

The assertions say what a meaningful percentage should be for representative inputs. They do not inspect private variables or repeat the calculation in a second function that could share the same mistake.

Choose edge cases from the contract: zero total, a negative count or more completed items than planned. In your own application, decide whether such inputs should be clamped, rejected or impossible at an earlier boundary. A test should document that decision rather than hide it.

Next use widget tests to verify that an accepted operation produces the expected visible result. Keep the pure calculation test fast and independent of rendering.

Practice and verification

Change the calculation to introduce an off-by-one error and verify the test fails. Add tests for a parser with malformed JSON and a repository failure without making a real request.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.