Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bloc was not initialized in Widget test cases #627

Open
GowthamanRavichandran3 opened this issue May 11, 2023 · 3 comments
Open

Bloc was not initialized in Widget test cases #627

GowthamanRavichandran3 opened this issue May 11, 2023 · 3 comments
Labels
type-documentation A request to add or improve documentation

Comments

@GowthamanRavichandran3
Copy link

GowthamanRavichandran3 commented May 11, 2023

I utilized Container and Text widgets in Flutter to create a basic example, and also incorporated a test case for my sample. However, during the test run(widget test case), I encountered a null exception as the bloc was not initialized. I have included my sample for your convenience. Is there a solution to address this issue?

Main.dart file

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:widget_test_case/bloc/resize_bloc.dart';

void main() => runApp(BlocProvider<ResizeBloc>(
      create: (c) => ResizeBloc(),
      child: MyApp(),
    ));

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: BlocBuilder<ResizeBloc, ResizeState>(builder: (context, state) {
          if (state is SelectinState) {
            return Builder(builder: (c) {
              return Center(
                child: GestureDetector(
                    onTap: () {
                      BlocProvider.of<ResizeBloc>(context).add(DummyEvent());
                    },
                    child: Text('State: ${state.items}')),
              );
            });
          }
          return GestureDetector(
            onTap: () {
              BlocProvider.of<ResizeBloc>(context).isSelected.value++;
              BlocProvider.of<ResizeBloc>(context).add(SelectinEvent('items'));
            },
            child: ValueListenableBuilder(
              valueListenable: BlocProvider.of<ResizeBloc>(context).isSelected,
              builder: (context, value, child) => Center(
                child: Column(
                  children: [
                    Container(
                      color: Colors.red,
                      width: 100,
                      height: 100,
                    ),
                    Text(
                        '${BlocProvider.of<ResizeBloc>(context).isSelected.value}')
                  ],
                ),
              ),
            ),
          );
        }),
      ),
    );
  }
}
```

**Test case**
```
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:widget_test_case/bloc/resize_bloc.dart';
import 'package:widget_test_case/main.dart';

class TestBlocMock extends Mock implements ResizeBloc {}

void main() {
  ResizeBloc testBloc = TestBlocMock();

  group('description', () {
    testWidgets('Test', (WidgetTester tester) async {
      when(testBloc.stream).thenAnswer(
        (_) => Stream.fromIterable(
          [ResizeInitial()],
        ),
      );

      await tester.pumpWidget(
          BlocProvider<ResizeBloc>(create: (c) => testBloc, child: MyApp()));
      expect(find.text('State: itmes'), findsNWidgets(0));
    });
  });
}
```
@srawlins
Copy link
Member

Questions like this are best asked on a user forum like StackOverflow or the Flutter Discord server. They have more eyes than just the maintainers to look.

@yanok
Copy link
Contributor

yanok commented Jun 5, 2023

class TestBlocMock extends Mock implements ResizeBloc {}

This is a problem (it might be the problem you are facing, but can't tell for sure, there might be others as well). I don't really know what this ResizeBloc is, but unless it has a very specific API (all methods taking all nullable arguments and returning a nullable result), this way of using Mockito won't work in Dart >= 2.12. You have to use the code generator instead.

@srawlins @natebosch Should we update the docs and scrap all the examples without using codegen?

@srawlins
Copy link
Member

srawlins commented Jun 5, 2023

Should we update the docs and scrap all the examples without using codegen?

Yes.

@devoncarew devoncarew added type-documentation A request to add or improve documentation and removed Type: documentation labels Aug 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-documentation A request to add or improve documentation
Projects
None yet
Development

No branches or pull requests

4 participants