Closed5

Flutter の UnitTest を使ってみる

薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

前回

前回は Flutter の MethodChannel を使って下記4点を試してみた

  • MethodChannel を使って iOS SDK の機能を呼び出す
  • MethodChannel を使って iOS サードパーティライブラリを呼び出す
  • MethodChannel を使って Android SDK の機能を呼び出す
  • MethodChannel を使って Android サードパーティライブラリ を呼び出す

https://zenn.dev/tatsuyasusukida/scraps/e447fc5d19e9b7

薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

group, test, expected

準備コマンド

flutter create hello_test
cd hello_test
touch lib/counter.dart test/counter_test.dart

flutter create をすると flutter_test が dev_dependencies に含まれているので test や flutter_test を flutter pub add を使って追加する必要が無さそう

コーディング

hello_test/lib/counter.dart
class Counter {
  int value = 0;
  void increment() => value++;
  void decrement() => value--;
}
hello_test/test/counter_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:hello_test/counter.dart';

void main() {
  group('Counter', () {
    test('value should start at 0', () {
      expect(Counter().value, 0);
    });

    test('Counter value should be incremented', () {
      final counter = Counter();
      counter.increment();
      expect(counter.value, 1);
    });

    test('Counter value should be decremented', () {
      final counter = Counter();
      counter.decrement();
      expect(counter.value, -1);
    });
  });
}

実行コマンド

flutter test --reporter expanded test/counter_test.dart

実行結果

00:00 +0: Counter value should start at 0
00:00 +1: Counter Counter value should be incremented
00:00 +2: Counter Counter value should be decremented
00:00 +3: All tests passed!
薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

WidgetTest

準備コマンド

flutter create hello_widget_test
cd hello_widget_test
touch lib/my_widget.dart test/my_widget_test.dart

コーディング

hello_test/lib/my_widget.dart
import 'package:flutter/material.dart';

class MyWidget extends StatelessWidget {
  final String title;
  final String message;

  const MyWidget({
    super.key,
    required this.title,
    required this.message,
  });
  
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(title: Text(title)),
        body: Center(child: Text(message)),
      ),
    );
  }
}
hello_test/test/my_widget_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:hello_widget_test/my_widget.dart';

void main() {
  testWidgets('MyWidget has a title and message', (tester) async {
    await tester.pumpWidget(const MyWidget(title: 'T', message: 'M'));
    final titleFinder = find.text('T');
    final messageFinder = find.text('M');

    expect(titleFinder, findsOneWidget);
    expect(messageFinder, findsOneWidget);
  });
}

実行コマンド

flutter test --reporter expanded test/my_widget_test.dart

実行結果

00:00 +0: MyWidget has a title and message
00:00 +1: All tests passed!
このスクラップは2023/01/10にクローズされました