简体   繁体   中英

How to unit test connectivity package in Flutter

I'm using connectivity package and let's say I have the following code:

_connectionSubscription = Connectivity().onConnectivityChanged.listen((
    ConnectivityResult result) {
  if (result == ConnectivityResult.mobile ||
      result == ConnectivityResult.wifi && !isDataLoading) {
    _loadData();
  }
});

I want to simulate different states to see how is my code working in different cases.

So how we can test it in Flutter using package:flutter_test environment?

You can create a mock of the Connectivity class by implementing it. Then in the mock class, implement the methods as needed.

example:


enum ConnectivityCase { CASE_ERROR, CASE_SUCCESS }

class MockConnectivity implements Connectivity {
  var connectivityCase = ConnectivityCase.CASE_SUCCESS;

  Stream<ConnectivityResult> _onConnectivityChanged;

  @override
  Future<ConnectivityResult> checkConnectivity() {
    if (connectivityCase == ConnectivityCase.CASE_SUCCESS) {
      return Future.value(ConnectivityResult.wifi);
    } else {
      throw Error();
    }
  }

  @override
  Stream<ConnectivityResult> get onConnectivityChanged {
    if (_onConnectivityChanged == null) {
      _onConnectivityChanged = Stream<ConnectivityResult>.fromFutures([
        Future.value(ConnectivityResult.wifi),
        Future.value(ConnectivityResult.none),
        Future.value(ConnectivityResult.mobile)
      ]).asyncMap((data) async {
        await Future.delayed(const Duration(seconds: 1));
        return data;
      });
    }
    return _onConnectivityChanged;
  }

  @override
  Future<String> getWifiBSSID() {
    return Future.value("");
  }

  @override
  Future<String> getWifiIP() {
    return Future.value("");
  }

  @override
  Future<String> getWifiName() {
    return Future.value("");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM