How to test Cubit in Flutter

By November 10, 2020 December 15th, 2020 No Comments

Test Cubit

I am going to write this post as short as possible. So I am going to cut the talking about why creating test cubit on Flutter is good blah blah.

Follow next steps to test your Cubit classes if you are using the BloC pattern with the Cubit variation.

Installation packages:

We are going to use two packages, bloc_test and mockito

  test: ^1.3.0
  bloc_test: ^7.0.0


Write the first test

Add the folder test if you don’t have it.


Create your file name_cubit_test.dart.

void main() {
  group('StartupCubit Tests -', () {
    setUp(() => registerMock());

    tearDown(() => unregisterMock());

    group('fetchAlerts -', () {
          build:() {
            return AlertsCubit(getIt.get<ReportsRepository>());
          act: (c)=>c.fetchAlerts(),
          expect: <AlertsState>[

As you may know already, you can group your tests in a group.

Then use blocTest<YourTypeCubit,YourTypeState> instead of test so you will be able to test the Cubit. It has 3 parameters:

build: My function getMockedAndRegisterReportRepository creates a Mock of ReportRepository (using Mockito). Looks like this:

  var mockReportRepository = MockReportRepository();
          (_) async => <AlertModel>[] );
  getIt.registerFactory<ReportsRepository>(() =>mockReportRepository);

My goal is just to test the Cubit, not the repository, so I mock the ReportRepository and when method fetchAlerts is called I mock the result as an empty list. Note I use getIt as a dependency injector.

act: Just call to fetchAlerts of the Cubit.

expected: I expect the Cubit to emit two states, Loading and Loaded with an empty List.

Now if I run the test all looks good and the expected result matches the result.


And that is it!!


Author Ernie

More posts by Ernie