atereshkov
atereshkov

Reputation: 4555

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?

Upvotes: 3

Views: 2357

Answers (1)

Sergio Bernal
Sergio Bernal

Reputation: 2327

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("");
  }
}

Upvotes: 4

Related Questions