Flutter: ウィジェットテストの動きをシミュレータで表示する

Flutter: ウィジェットテストの動きをシミュレータで表示する

June 8, 2024

通常のテスト方法 #

flutter create でアプリを作成すると次のテストファイルが作られています。

myapp/test/widget_test.dart

// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

import 'package:myapp/main.dart';

void main() {
  testWidgets('Counter increments smoke test', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(const MyApp());

    // Verify that our counter starts at 0.
    expect(find.text('0'), findsOneWidget);
    expect(find.text('1'), findsNothing);

    // Tap the '+' icon and trigger a frame.
    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();

    // Verify that our counter has incremented.
    expect(find.text('0'), findsNothing);
    expect(find.text('1'), findsOneWidget);
  });
}

テストを実施するには以下コマンドを実行すれば良いです。

flutter test

テストの動きをシミュレータで表示する #

自分の意図した通りのテストができているのか、実行されている動作を画面上で確認したいときってありますよね?

そんなときは flutter run に続けてテスト対象のファイルをして実行しましょう。

flutter run test/widget_test.dart

To help debug widget tests, you can use the debugDumpApp() function to visualize the UI state of your test or simply flutter run test/widget_test.dart to see your test run in your preferred runtime environment such as a simulator or a device. During a flutter run session on a widget test, you can also interactively tap parts of the screen for the Flutter tool to print the suggested Finder.

https://flutter-website-staging.firebaseapp.com/testing/

実際にやってみた

widget_test.dart を次の通りに編集し flutter run test/widget_test.dart 実行してみます。

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:myapp/main.dart';

Future<void> _tapAddIconButton(WidgetTester tester) async {
  // Tap the '+' icon and trigger a frame.
  sleep(const Duration(seconds: 1));
  await tester.tap(find.byIcon(Icons.add));
  await tester.pump();
}

void main() {
  testWidgets('Counter increments smoke test', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(const MyApp());

    // Verify that our counter starts at 0.
    expect(find.text('0'), findsOneWidget);

    // Tap the button 5 times.
    const count = 5;
    for (var i = 0; i < count; i++) {
      await _tapAddIconButton(tester);
    }

    // Verify that our counter has incremented.
    expect(find.text('0'), findsNothing);
    expect(find.text(count.toString()), findsOneWidget);
  });
}

Flutter Widget Test