【Flutter】iOSで Integration Test を利用したスクリーンショット自動化が失敗する

2022/10/22 18:33公開
Table of Contents
  1. 事象
  2. 解決方法

事象

FlutterでIntegration Test内でのスクリーンショット撮影が、iOSでのみ以下のようなエラーで失敗する。

Failure in method: screenshot
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞═════════════════
The following MissingPluginException was thrown running a test:
MissingPluginException(No implementation found for method
captureScreenshot on channel plugins.flutter.io/integration_test)

When the exception was thrown, this was the stack:
#0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:294:7)
<asynchronous suspension>
#1      IOCallbackManager.takeScreenshot (package:integration_test/_callback_io.dart:94:33)
<asynchronous suspension>
#2      IntegrationTestWidgetsFlutterBinding.takeScreenshot (package:integration_test/integration_test.dart:190:39)
<asynchronous suspension>
#3      takeScreenshot (file:///Users/chika/StudioProjects/submon/integration_test/screenshot_test.dart:57:3)
<asynchronous suspension>
#4      main.<anonymous closure> (file:///Users/chika/StudioProjects/submon/integration_test/screenshot_test.dart:26:5)
<asynchronous suspension>
#5      testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:171:15)
<asynchronous suspension>
#6      TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:841:5)
<asynchronous suspension>

The test description was:
  screenshot
═════════════════════════════════════════════════════════════════

これは以下のIssueでも議論されているが、未だにCloseされていない。

[integration_test] Plugin not registered unless running via XCTest #91668

解決方法

以下のページを参考にした。

Grabs screenshots from your Flutter app on multiple platforms (iOS and Android)

flutter(Flutter SDKのフォルダー)/packages/integration_test/ios/Classes/IntegrationTestPlugin.mを開き、registerWithRegistrarメソッドの内容を以下のように書き換える。

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
  // No initialization happens here because of the way XCTest loads the testing
  // bundles.  Setup on static variables can be disregarded when a new static
  // instance of IntegrationTestPlugin is allocated when the bundle is reloaded.
  // See also: https://github.com/flutter/plugins/pull/2465
  [[IntegrationTestPlugin instance] setupChannels:registrar.messenger]; // 追加
}

そのままビルドして実行すると、撮影が可能になる。