title: Flutter Widget Testing for BlocBuilder Widgets
body: <p>I have a Widget which uses bloc builder to map the different state of widget.</p>
  <pre><code>class BodyWidget extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
          return BlocBuilder&lt;NewsBloc, NewsState&gt;(builder: (context, state) {
            return state.map(
              .....
            );
          });
        }
      ....
      }
  </code></pre>
  <p>The <code>BodyWidget</code> is created in a Widget with BlocProvider.</p>
  <pre><code>class MainPage extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return BlocProvider(
        create: (context) =&gt;
            getIt&lt;NewsBloc&gt;()..add(const NewsEvent.fetchNewsData()),
        child: BodyWidget(),
      );
    }
  ....
  }
  </code></pre>
  <p>And the NewsBloc is defined as</p>
  <pre><code>@injectable
  class NewsBloc extends Bloc&lt;NewsEvent, NewsState&gt; {
    final GetNews getNews;
    NewsBloc({
      @required this.getNews,
    }) : super(const _Initial());
  
    @override
    Stream&lt;NewsState&gt; mapEventToState(
      NewsEvent event,
    ) async* { ... }
  }
  </code></pre>
  <p>I am using <a href="https://pub.dev/packages/get_it" rel="nofollow noreferrer">get_it</a> and <a href="https://pub.dev/packages/injectable" rel="nofollow noreferrer">injectable</a> for Dependency Injection.</p>
  <p>Now I am trying to write a simple widget test for <code>BodyWidget</code> and I am not so sure how to inject all these dependency in test.</p>
  <pre><code>class MockBuildContext extends Mock implements BuildContext {}
  
  class MockNewsBloc extends Mock implements NewsBloc {}
  
  void main() {
    ForYouNewsTab _widget;
    MockBuildContext _context;
    NewsBloc _newsBloc;
  
    Widget makeTestableWidgets({Widget child}) {
      return MaterialApp(
        home: Scaffold(
          // body: BlocProvider(
          //   create: (_context) =&gt; getIt&lt;NewsBloc&gt;(),
          //   child: child,
          // ),
          body: child,
        ),
      );
    }
  
    setUp(() {
      _context = MockBuildContext();
      _widget = ForYouNewsTab();
    });
  
    test('ForYouNewsTab is sub class of StatelessWidget', () {
      expect(_widget, isA&lt;StatelessWidget&gt;());
    });
  
    testWidgets('should return sized box for initial state',
        (WidgetTester tester) async {
      await tester.pumpWidget(makeTestableWidgets(child: _widget));
    });
  }
  </code></pre>
  <p>I did search in stackoverflow, but could not found a solution that works form me.</p>