Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@reinaldomoreira
Created January 24, 2020 18:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reinaldomoreira/98e6d8ce1c296defe66fb064bbc2733b to your computer and use it in GitHub Desktop.
Save reinaldomoreira/98e6d8ce1c296defe66fb064bbc2733b to your computer and use it in GitHub Desktop.
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() => runApp(BlocProvider<TestBloc>(
create: (c) => TestBloc(),
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<TestBloc, TestState>(builder: (context, state) {
if (state == null) {
return Container();
// throw Exception('state is null');
}
return Builder(builder: (c) {
return Center(
child: Text('State: ${state.text}'),
);
});
}),
),
);
}
}
class TestBloc extends Bloc<TestEvent, TestState> {
@override
TestState get initialState => TestState('initialState');
@override
Stream<TestState> mapEventToState(TestEvent event) async* {
yield TestState('yield from mapEvent');
}
}
class TestEvent {}
class TestState {
TestState(this.text);
final String text;
}
import 'package:bloc_test/bloc_test.dart';
import 'package:fluttebloc/main.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
class TestBlocMock extends Mock implements TestBloc {}
void main() {
testWidgets('Test', (WidgetTester tester) async {
final testBloc = TestBlocMock();
when(testBloc.initialState).thenReturn(TestState('Initial mocked'));
whenListen<TestEvent, TestState>(
testBloc,
Stream.fromIterable([
TestState('First emission'),
TestState('Second emission'),
]),
);
await tester.pumpWidget(
BlocProvider<TestBloc>(create: (c) => testBloc, child: MyApp()));
await tester.pump(Duration.zero);
// expect(find.text('First emission'), findsOneWidget);
expect(find.text('State: Second emission'), findsOneWidget);
});
}
@felangel
Copy link

Hey! This is happening because instead of mocking initialState you need to mock state.

class TestBlocMock extends MockBloc<TestEvent, TestState> implements TestBloc {} // extend MockBloc rather than Mock

void main() {
  testWidgets('Test', (WidgetTester tester) async {
    final testBloc = TestBlocMock();
    when(testBloc.state).thenReturn(TestState('Initial mocked')); // stub state rather than initialState
    whenListen<TestEvent, TestState>(
      testBloc,
      Stream<TestState>.fromIterable([
        TestState('First emission'),
        TestState('Second emission'),
      ]),
    );
    await tester.pumpWidget(
      BlocProvider<TestBloc>(create: (c) => testBloc, child: MyApp()),
    );
    await tester.pump(Duration.zero);
    expect(find.text('State: Second emission'), findsOneWidget);
  });
}

Hope that helps! 👍

@gerryau
Copy link

gerryau commented May 22, 2022

How would I go about testing something like this when I am using getIt for dependency injection? I have tried adding:

setUp()
getIt.registerFactory<ProjectFormCubit>(() => MockProjectFormCubit());

And then reset() in teardown.

But I have not had any success. The widget under test is using:
BlocProvider with:
getIt<ProjectFormCubit>()..initialised(optionOf(editedProject)),`

@Muhammed-Essam
Copy link

I used
setUpAll(){() => GetIt.registerFactory(() => MockProjectFormCubit())
}
and it works fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment