Search code examples
flutterflutter-test

How do you simulate Flutter state restoration inside an automated test?


I have a widget that uses state restoration and does some extra logic in the restoreState method. I'd like to test that logic, so I'm wondering if there's a way to trigger state restoration from within a Flutter test.

I can manually test the logic with an Android emulator using "Don't keep activities" which will trigger restoreState when the application is restarted, but I want to do it in an automated test.


Solution

  • This can be achieved by using a widget test (An Introduction to Widget testing—by Flutter). In the automated test, the Flutter app can be forced to restart and restore its state using the instance method restartAndRestore() from the WidgetTester class.

    For example:

    testWidgets('Description of the test', (WidgetTester tester) async {
      await tester.pumpWidget(MyWidget());
      // modify the state of the app
      await tester.restartAndRestore(); // restoreState gets called here
      // verify the custom logic in restoreState executed successfully
    });