Last updated: November 9, 2026

Bahasa Indonesia | English

A feature that works on one device may still have hidden problems. In this codelab, you will write tests that check application behavior, catch regressions, and help keep code reliable as the app grows.

Learning objectives

By the end of this codelab, you should be able to:

What you need

1. Choose the right kind of test

TypeWhat it checksExample
UnitA function or object without rendering UITask-title validation or a business rule
WidgetThe output and interaction of one or more widgetsA form shows feedback for invalid input
IntegrationAn end-to-end app flow on a device or emulatorA user adds a task and sees it in the list

Unit tests are usually the fastest and easiest to maintain. Widget tests check UI without launching the app on a device. Integration tests cover a broader flow, but take longer to run and maintain.

2. Make code easier to test

Business logic mixed into widgets and network calls is hard to test in isolation. Separate responsibilities: widgets handle presentation and interaction, while repositories handle data sources. Pass a repository through a constructor or abstraction so a test can replace it with controlled data.

1. Test behavior

This example checks a simple rule: a task title is valid when it contains non-whitespace text.

bool isValidTaskTitle(String value) {
  return value.trim().isNotEmpty;
}

Create test/is_valid_task_title_test.dart. The flutter_test package is included in Flutter projects.

import 'package:flutter_test/flutter_test.dart';
import 'package:testing_lab/is_valid_task_title.dart';

void main() {
  group('isValidTaskTitle', () {
    test('accepts a title with text', () {
      expect(isValidTaskTitle('Learn Flutter'), isTrue);
    });

    test('rejects empty or whitespace-only text', () {
      expect(isValidTaskTitle(''), isFalse);
      expect(isValidTaskTitle('   '), isFalse);
    });
  });
}

Replace the package name in the import statement with the name from your pubspec.yaml.

2. Use Arrange, Act, Assert

Add relevant edge cases, such as empty input, whitespace, boundary values, or expected failures. Do not test only the happy path.

1. Define a data-source contract

Avoid relying on a live API in unit tests. Network access, authentication, and server data can change, making tests slow or inconsistent. Define a small contract for the feature:

abstract interface class TaskRepository {
  Future<List<String>> getTasks();
}

class TaskService {
  TaskService(this._repository);

  final TaskRepository _repository;

  Future<List<String>> loadTasks() {
    return _repository.getTasks();
  }
}

2. Replace the API with a fake repository

A fake is a small implementation whose behavior is controlled by the test. It lets you check both success and failure without an internet connection.

class FakeTaskRepository implements TaskRepository {
  FakeTaskRepository({this.tasks = const [], this.error});

  final List<String> tasks;
  final Exception? error;

  @override
  Future<List<String>> getTasks() async {
    if (error != null) throw error!;
    return tasks;
  }
}

test('returns data from the repository', () async {
  final service = TaskService(
    FakeTaskRepository(tasks: ['Read the material']),
  );

  expect(await service.loadTasks(), ['Read the material']);
});

Add a failure test to make sure an error is not silently turned into an empty list. Test the error behavior your application is designed to provide.

1. Build a widget and check its output

Widget tests run with flutter_test. Use pumpWidget to render the UI, then find elements and check what users can see.

testWidgets('shows the task page title', (tester) async {
  await tester.pumpWidget(
    const MaterialApp(
      home: Scaffold(
        body: Text('Task list'),
      ),
    ),
  );

  expect(find.text('Task list'), findsOneWidget);
});

2. Test user interactions

To test a form or button, enter text with enterText, tap a control with tap, then call pump or pumpAndSettle to render the updated UI.

await tester.enterText(
  find.byKey(const Key('task-title-field')),
  'Read the material',
);
await tester.tap(find.byKey(const Key('save-task-button')));
await tester.pumpAndSettle();

expect(find.text('Read the material'), findsOneWidget);

Add a Key to a control when finding it by visible text or widget type is not clear enough. Also test important states such as invalid input, loading, empty data, and errors.

1. Run a flow on a device

Integration tests check multiple parts of an app working together. Flutter provides the integration_test package. If it is not already in your project, add it under dev_dependencies in pubspec.yaml, then run flutter pub get:

dev_dependencies:
  integration_test:
    sdk: flutter

Put the test in integration_test/app_test.dart and initialize its binding as shown here:

import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:testing_lab/main.dart' as app;

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('a user can add a task', (tester) async {
    app.main();
    await tester.pumpAndSettle();

    await tester.enterText(
      find.byKey(const Key('task-title-field')),
      'Read the material',
    );
    await tester.tap(find.byKey(const Key('save-task-button')));
    await tester.pumpAndSettle();

    expect(find.text('Read the material'), findsOneWidget);
  });
}

Use keys that match your app. Run the test on a connected emulator or device:

flutter test integration_test/app_test.dart -d <device_id>

2. Prevent regressions with a test

When you find and fix a bug, add a test that fails before the fix and passes afterward. Run the full suite regularly with flutter test, not just the test you have just added.

Use a key feature from your project. If you do not have one yet, make a simple task list. The goal is to test behavior from logic through the app flow, not to maximize the number of tests.

  1. Describe the behavior: write down at least three scenarios, including an edge case and a failure.
  2. Test the logic: write unit tests for validation or a business rule. Group related cases with group.
  3. Test a dependency: isolate data access behind a repository and provide a fake for success and error cases.
  4. Test the UI: check the initial display, invalid input, and a successful user action.
  5. Test the main flow: write one integration test for an important flow across app components.
  6. Run the checks: use flutter test, flutter test integration_test/app_test.dart -d <device_id>, and flutter analyze. Resolve failures before moving on.

When a test fails, read the output to identify the test and unmet condition. Check that the cause is not test order, shared data, or network dependence.

1. Treat coverage as a clue

To generate a coverage report for unit and widget tests, run:

flutter test --coverage

Coverage shows which parts of the code ran during tests; it does not guarantee that all behavior was checked. Review important branches and edge cases instead of adding assertions-free tests just to raise a percentage.

2. Assignment

  1. Add unit and widget tests for a key feature in your project, including a success case, invalid input, and a relevant error.
  2. Add one integration test for the main flow. If you cannot run it on a device, describe the blocker and include the command you tried.
  3. Record your scenarios, flutter test results, analysis results, and unresolved findings in README.md.
  4. Submit your changes through the Git repository as directed by your instructor.

Reflection

Supporting references