Week 12

Testing and Quality Assurance

Mobile Programming

Unit Testing | Widget Testing | Integration Testing | Testable Architecture

Write tests that help us change code with greater confidence.

Learning Objectives

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

  1. Choose the right type of test for a feature.
  2. Write unit tests for business logic and edge cases.
  3. Check Flutter widget output and interactions.
  4. Separate dependencies to make code easier to test.
  5. Test an app flow and critically review code coverage.

Why Test an App?

  • A small change can quietly affect another feature.
  • Tests provide evidence that important scenarios still work.
  • Good tests document the behavior we expect.
  • Automation makes repeated checks faster and more consistent.

Testing cannot prove an app is perfect. It helps us catch issues earlier and understand the impact of a change.

Three Types of Tests

Type Focus Example
Unit An isolated function or object Validate a task title
Widget UI and widget interaction Form rejects empty input
Integration A flow across app components Add a task and see it in the list

Start with fast unit tests. Add widget and integration tests for behavior involving UI or multiple parts of the app.

Code That Is Easy to Test

  • Keep business rules out of widgets.
  • Put data access behind a repository contract.
  • Provide dependencies through constructors.
  • Replace real services with fakes in tests.
Widget → Service / use case → Repository → API
                           ↑
                    Fake repository in tests

This separation makes tests focused and independent of the network.

Unit Tests: Check the Rule

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

Scenarios to check:

  • A title with text is accepted.
  • Empty text is rejected.
  • Whitespace-only text is rejected.

Test structure: Arrange (prepare), Act (run), Assert (check).

Write Useful Tests

test('rejects a whitespace-only title', () {
  expect(isValidTaskTitle('   '), isFalse);
});
  • Name the behavior being checked.
  • Cover relevant normal, boundary, and failure cases.
  • Make sure the test would fail if the behavior broke.
  • Avoid tests that run code without checking a result.

Run the full suite with flutter test.

Testing Async Code

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

class TaskService {
  TaskService(this.repository);
  final TaskRepository repository;

  Future<List<String>> loadTasks() => repository.getTasks();
}

A repository abstraction lets tests replace the data source.

Use a Fake, Not a Live API

class FakeTaskRepository implements TaskRepository {
  FakeTaskRepository(this.tasks);
  final List<String> tasks;

  @override
  Future<List<String>> getTasks() async => tasks;
}
  • Test results do not depend on the internet or server.
  • Success and error scenarios are under your control.
  • Tests are faster and easier to repeat.
  • Make sure errors are not silently treated as empty data.

Widget Testing

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

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

pumpWidget renders the UI. find locates elements, and expect checks the result.

Check User Interactions

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 when a control is hard to find by text or widget type. Also check loading, empty data, invalid input, and error states.

Integration Testing

Test an important flow on an emulator or device:

  1. Open the app and wait for the UI.
  2. Enter a task title.
  3. Tap the save button.
  4. Confirm the task appears in the list.
flutter test integration_test/app_test.dart -d <device_id>

Choose a few high-risk flows. Integration tests take longer than unit and widget tests.

Regression and Code Coverage

  • When fixing a bug, add a test that fails before the fix.
  • Rerun the suite with flutter test.
  • Generate a coverage report with flutter test --coverage.
  • Review important branches and uncovered edge cases.

Coverage percentage is not a quality score by itself. What matters is whether important behavior is actually tested.

Lab: Test a Task List Feature

  1. Write success, invalid-input, and failure scenarios.
  2. Add unit tests for validation or a business rule.
  3. Isolate data access and create a fake repository.
  4. Check the UI and interactions in a widget test.
  5. Test one key flow with an integration test.
  6. Run flutter test and flutter analyze, then document the results.

Choose tests for their risk and value, not their line count.

Review Tests Carefully

Before calling the work done, ask:

  • Would a test fail if the feature actually broke?
  • Have important edge cases and errors been checked?
  • Are the tests independent of network access and execution order?
  • Can a teammate understand what each test is checking?

AI can help suggest ideas, but you are responsible for reviewing the tests and results.

References and Next Steps

  • Flutter testing: docs.flutter.dev/testing/overview
  • Widget testing: docs.flutter.dev/cookbook/testing/widget/introduction
  • Integration testing: docs.flutter.dev/testing/integration-tests
  • Dart test package: pub.dev/packages/test

After this session: add tests for a key feature in your project and document the scenarios and results in README.md.