okuzawatsの日記

Android / Kotlin Enthusiast 🤖

Unit Testing of Flutter Dart Code with GitHub Actions

Summary

Add Unit Testing

Add Dev-Dependencies on test

First of all, add dev_dependencies on test in pubspec.yaml and you may need to flutter pub get as usual.

dev_dependencies:
  test:

Define a Sample Target Class

We need a class to be unit tested, so let’s define a simple arithmetic class as lib/arithmetic.dart.

class Arithmetic {
  int add(int a, int b) => a + b;
}

Define Test Cases

Now we can define test cases of unit testing. In order to distinguish unit tests from UI tests, I made unit directory under test. So the path to test code is like test/unit/arithmetic_test.dart. The file names of test codes should have _test suffix with the target file name.

The unit test codes are like below. We can define setUp and tearDown like XUnit, and define test cases with test function. Now we can run unit tests locally with flutter test test/unit/*_test.dart or flutter test test/unit/**/*_test.dart.

import 'package:yourawesomeapp/arithmetic.dart';
import 'package:test/test.dart';

void main() {
  Arithmetic target;

  setUp(() {
    target = Sum();
  });

  tearDown(() {
    target = null;
  });

  test('sum of 4 + 8 = 12', () {
    expect(target.add(4, 8), equals(12));
  });

  test('sum of 5 + 6 = 11', () {
    expect(target.add(5, 6), equals(11));
  });
}

Define GitHub Actions Workflow to Unit Testing

Now is the time for define a workflow of GitHub Actions to unit testing. As always, with the help of subosito/flutter-action, we can run flutter commands on GitHub Actions, so the workflow would be below.

The yaml file would be in .github/workflows/unittest.yaml.

name: unit test

on:
  pull_request:
    types: [opened, synchronize]
  push:
    branches:
      - main

jobs:
  unittest:
    name: flutter unit test
    runs-on: ubuntu-latest
    steps:
      - name: set up repository
        uses: actions/checkout@v1
      - name: set up java
        uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          channel: "stable"
      - name: flutter pub get
        run: flutter pub get
      - name: flutter unit test
        run: flutter test test/unit/**/*_test.dart

That’s all. Now unit testing is run when making a pull request and CI will fails if any test case fails.

#Flutter #GitHub Actions #Dart

About me 😎

profile

茨城県つくば市在住のソフトウェアエンジニアです。専門領域はAndroidアプリ開発で、特にアーキテクチャに興味があります。某社でAndroidアプリ開発のテックリードをしています。

Jetpack ComposeによるAndroid MVVMアーキテクチャ入門の著者です。

👉 もっと詳しく

Writing 📝

Android MVVMアーキテクチャ入門

Androidアプリ開発の初学者に向けた、MVVM(Model-View-ViewModel)アーキテクチャの入門書を書きました。初学者の方を確実にネクストレベルに引き上げる技術書です。

👉 もっと詳しく

See Also 👀