Flutter:如何模拟流

时间:2018-11-26 08:34:04

标签: testing stream mocking flutter

我正在使用bloc模式,现在我来测试UI。我的问题是:如何模拟流? 这是我的代码: 我给RootPage类提供了一个可选的嘲笑值,如果这个嘲笑值不为null,我会将其设置为实际的_bloc

class RootPage extends StatefulWidget {

  final loggedOut;
  final mockBlock;
  RootPage(this.loggedOut, {this.mockBlock});

  @override
  _RootPageState createState() => _RootPageState();
}


class _RootPageState extends State<RootPage> {

  LoginBloc _bloc;

     @override
      void initState() {
        super.initState();
        if (widget.mockBlock != null)
          _bloc = widget.mockBlock;
        else
          _bloc = new LoginBloc();
        if (widget.loggedOut == false)
        _bloc.startLoad.add(null);
      }

    ...

 @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: _bloc.load,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Column(
                children: <Widget>
                     ...

这是我尝试过的:

  testWidgets('MyWidget', (WidgetTester tester) async {
    MockBloc mockBloc = new MockBloc();
    MockTokenApi mockTokenApi = new MockTokenApi();

    await tester.pumpWidget(new MaterialApp(
        home: RootPage(false, mockBlock: mockBloc)));

    when(mockBloc.startLoad.add(null)).thenReturn(mockBloc.insertLoadStatus.add(SettingsStatus.set));   //this will give in output the stream that the StreamBuilder is listening to (_bloc.load)
    });
   await tester.pump();
    expect(find.text("Root"), findsOneWidget);

  });

我一直获得的结果是:

  

方法'add'在null上被调用

调用_bloc.startLoad.add(null)

1 个答案:

答案 0 :(得分:0)

您可以通过使用 mockito 创建模拟类来创建模拟流。这是一个如何实施的示例。

import 'package:mockito/mockito.dart';

class MockStream extends Mock implements Stream<int> {}

void main() async {
  var stream = MockStream();
  when(stream.first).thenAnswer((_) => Future.value(7));
  print(await stream.first);

  when(stream.listen(any)).thenAnswer((Invocation invocation) {
    var callback = invocation.positionalArguments.single;
    callback(1);
    callback(2);
    callback(3);
  });

  stream.listen((e) async => print(await e));
}