如何在Bloc单元测试中模拟连接性?

时间:2020-05-19 08:42:21

标签: unit-testing flutter dart flutter-test

我正在使用此package,并且在一个群组中具有以下连接

Connectivity _connectivity = Connectivity();
StreamSubscription _connectivityStreamSubscription;

ConnectivityBloc() {
    _connectivityStreamSubscription = _connectivity.onConnectivityChanged.listen((connectivityResult) {
      if (connectivityResult == ConnectivityResult.wifi) {
        add(ConnectivityEventConnectEvent());
      } else {
        add(ConnectivityEventDisconnectEvent());
      }
    });
  }

我正在尝试测试块,但是我正在努力在单元测试中模拟StreamSubscription。那么我们如何在bloc_test中模拟StreamSubscription?

1 个答案:

答案 0 :(得分:0)

我发现我没有将Connectivity实例传递给集团。

ConnectivityBloc(this._connectivity) {

我嘲笑了Mockito的连通性。

class MockConnectivity extends Mock implements Connectivity {}

然后我可以通过具有所需的ConnectivityResult的流

when(mockConnectivity.onConnectivityChanged).thenAnswer(
      (_) => Stream<ConnectivityResult>.fromIterable([ConnectivityResult.mobile, ConnectivityResult.wifi]));