简体   繁体   English

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

[英]How to mock connectivity in bloc unit-tests?

I'm using this package and I have a following connectivity in a bloc我正在使用这个package并且我在一个集团中有以下连接

Connectivity _connectivity = Connectivity();
StreamSubscription _connectivityStreamSubscription;

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

I'm trying to test the bloc, however I'm struggling to mock the StreamSubscription in unit tests.我正在尝试测试该集团,但是我正在努力在单元测试中模拟 StreamSubscription。 So how can we mock StreamSubscription in bloc_test?那么我们如何在 bloc_test 中模拟 StreamSubscription 呢?

I've figured it out I didn't pass the instance of Connectivity to bloc.我发现我没有将 Connectivity 的实例传递给 bloc。

ConnectivityBloc(this._connectivity) {

I have mocked the Connectivity with Mockito.我用 Mockito 模拟了连接。

class MockConnectivity extends Mock implements Connectivity {}

and then I could just pass the Stream with ConnectivityResult I wanted然后我可以通过 Stream 和我想要的 ConnectivityResult

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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