Android / Kotlin Enthusiast 🤖

Unit Testing of Flutter Dart Code with GitHub Actions


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.


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

    types: [opened, synchronize]
      - main

    name: flutter unit test
    runs-on: ubuntu-latest
      - name: set up repository
        uses: actions/checkout@v1
      - name: set up java
        uses: actions/setup-java@v1
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
          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 😎



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

👉 もっと詳しく

Writing 📝

Android MVVMアーキテクチャ入門


👉 もっと詳しく

See Also 👀