Unit Testing in Flutter


In this lesson we'll cover:

The Code for This Lesson

You can check out the step/step08 branch here which will contain the code for this lesson.

Ensure the flutter_test dependency exists

  flutter_test: any

What Unit Tests Are

  1. Flutter defines tests categorized into three different types, unit, widget and integration.
  2. Unit tests are meant to test a specific class or set of business logic - basically a small, focused "unit" of work.

How to Structure Our test directory

  1. First, remove the tests/widget_test.dart file, we'll create it later as it's not needed right now.
  2. Create tests/unit/location_test.dart

Testing Our fetchAll() Method

// test/unit/location_test.dart

import 'package:flutter_test/flutter_test.dart';
import 'package:tourismandco/models/location.dart';

void main() {
  test('Locations can be fetched', () {
    final locations = Location.fetchAll();

    expect(locations.length, greaterThan(0));

  // NOTE we'll add more tests here later in this lesson
  1. Here, we fetch a list of locations and ensure we get at least one.
  2. What's cool is that once we wire up to a real web service API, we can still ensure the tests pass and our app can still use Location.fetchAll().

Running Tests

  1. The traditional way to run tests is flutter test test/<your test file> so in our case flutter test test/unit/location_test.dart
  2. We can easily run tests though using Visual Studio Code by right clicking the file itself and choosing 'Start Debugging'
  3. Lastly, if we're using Visual Studio Code, we can hover over the individual test cases and run them.

What's Next?

We still should test our individual widgets, as well as an entire app 'walkthrough' where the tests run the app and tap on the important parts to ensure they're working. We'll cover that next.

Testing Our fetchByID() Method

  1. Let's add another test, this time with a different description.
// test/unit/location_test.dart

// ...

test('Locations can be fetched by ID', () {
  final locations = Location.fetchAll();

  for (Location l in locations) {
    final fetchedLocation = Location.fetchByID(l.id);
    expect(fetchedLocation, isNotNull);
    expect(fetchedLocation.id, equals(l.id));


That's it! Very simple but we'll expand on this by adding widget and integration tests.