[Flutter]ファイル書き込みを伴うテスト

2020/10/10に公開

概要

  • MethodChannelで実行環境のテンポラリなパスを参照するようモックする
  • path_provider#getApplicationDocumentsDirectory() はFlutter内の関数なので testWidgets() で実行する必要がある
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider/path_provider.dart';

Future<File> write(String filename, String contents) async {
  final directory = await getApplicationDocumentsDirectory();
  final path = directory.path;

  final file = File('$path/$filename');

  file.writeAsStringSync(contents);

  return file;
}

void main() {
  setUpAll(() async {
    final directory = await Directory.systemTemp.createTemp();

    const MethodChannel('plugins.flutter.io/path_provider')
        .setMockMethodCallHandler((MethodCall methodCall) async {
      if (methodCall.method == 'getApplicationDocumentsDirectory') {
        return directory.path;
      }
      return null;
    });
  });
  testWidgets('write text to file', (WidgetTester tester) async {
    final file = await write('hello.txt', 'Hello World');
    expect(file.readAsStringSync(), 'Hello World');
  });
}

References

Discussion