首页 > 解决方案 > 在颤动的单元测试中面临方法通道互联网连接的问题

问题描述

我在使用“连接”库像这样在商店类中调用 api 时检查了互联网连接。

    Future<bool> callApi() async {

    final isInternet = await Util.checkInternetAndShowDialog(context);

    if (isInternet) {

      final future = _repository.callApi();

      var res = await future;

      return true;

    }

return false;

    }

在 Util 类中检查网络连接,如下所示:

class Util {

  static Future<bool> checkInternetAndShowDialog(BuildContext context) async{
    var internet = await NetworkConnectivity.rechability();
    if (internet == false) {
      AlertMessage().showAlertDialog(context, 'error message');
    }
    return internet;
  }

}

在 NetworkConnectivity 类中,使用 Connectivity 库检查网络连接。

class NetworkConnectivity {

static Future<bool> rechability() async {

    var connectivityResult = await (Connectivity().checkConnectivity());

    if (connectivityResult == ConnectivityResult.mobile) {

      return true;

    } else if (connectivityResult == ConnectivityResult.wifi) {

      return true;

    }

    return false;

  }

}

我的测试用例代码如下:

test('call api successfully', () async {

      when(mockStore.callApi()).thenAnswer((realInvocation) => Future.value());
      expect(await store.callApi(), true);
    });

所以在编写单元测试时,我面临连接和方法通道的错误。 连接错误图像

任何人都可以帮助我如何在单元测试中模拟互联网连接并通过颤振测试。我会为此感谢的。

标签: flutterdartflutter-testconnectivity

解决方案


推荐阅读