lundi 26 novembre 2018

Flutter: how to mock a stream

I´m using the bloc pattern and now I came to test the UI. My question is: how to mock streams? This is the code that I have: I give to the RootPage class an optional mockBloc value and I will set it to the actual _bloc if this mockBloc is not null

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>
                     ...

This is what I´ve tried:

  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
    });
   await tester.pump();
    expect(find.text("Root"), findsOneWidget);

  });

The result that I achieve is always to get:

The method 'add' was called on null

when _bloc.startLoad.add(null) is called

Aucun commentaire:

Enregistrer un commentaire