我正在使用connectivity package,假设我有以下代码:
_connectionSubscription = Connectivity().onConnectivityChanged.listen((
ConnectivityResult result) {
if (result == ConnectivityResult.mobile ||
result == ConnectivityResult.wifi && !isDataLoading) {
_loadData();
}
});
我想模拟不同的状态,以查看我的代码在不同情况下如何工作。
那么我们如何使用package:flutter_test环境在Flutter中对其进行测试?
答案 0 :(得分:1)
您可以通过实现它来创建Connectivity类的模拟。然后在模拟类中,根据需要实现方法。
示例:
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("");
}
}