有没有办法在 Flutter 单元测试中测试 AppLifecycleState 更改?

Rea*_*nkm 2 unit-testing flutter

当应用程序移到后台 (AppLifecycleState.paused) 时,我的应用程序将用户首选项写入本地文件,我想为此行为编写测试。

有没有办法在单元测试中模仿这一点?或者这是需要作为集成测试完成的事情吗?

小智 8

tester.binding.handleAppLifecycleStateChanged is definitly the correct way to test it.

ex: Statefull widget on the home page that listen to app lifecycle

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      pushLoginPage(context);
    }
  }
Run Code Online (Sandbox Code Playgroud)

If you want to test this, you have to paused first, and then resumed to ensure Flutter navigation.


Ian*_*son 6

您可以binding.handleAppLifecycleStateChanged在单元测试中调用来伪造应用程序进出前台。

  • 您可以通过“final binding = TestWidgetsFlutterBinding.ensureInitialized();”获得绑定。 (2认同)