Flutter: how to mock Bloc Flutter: how to mock Bloc flutter flutter

Flutter: how to mock Bloc


If I understood correctly, you are mocking some service that is used by the searchBloc. I personally try to design the app in a way that the app only depends on a bloc and the bloc may depend on some other services. Then when I would like to make a widget test, I only need to mock the bloc. You can use bloc_test package for that.

There is this example on the bloc_test page for stubbing a counterBloc:

// Create a mock instancefinal counterBloc = MockCounterBloc();// Stub the bloc `Stream`whenListen(counterBloc, Stream.fromIterable([0, 1, 2, 3]));

however, I often do not need to stub the bloc stream and it is enough to emit the state, like this

when(counterBloc.state).thenAnswer((_) => CounterState(456));

Hope this helps.


Have a look at a post from David Anaya which deal with Unit Testing with “Bloc” and mockito.

The last version of his example is here


Sometimes widgets require a little time to build. Try with:

await tester.pumpWidget(generateApp(_searchView));await tester.enterText(find.byKey(Key("searchBar")), "a");await tester.pump(Duration(seconds: 1));expect(find.byType(Card), findsOneWidget);