Mocking Hive with Mockito Flutter

Issue

So basically, I want to check whether I’ve passed whatever I need to pass to the HiveInterface and Box when I want to store something.

test.dart:

group('cacheStoraygeUser', () {
    test(
      'should call HiveInterface and Box to cache data',
      () async {
        when(mockHiveInterface.openBox(any)).thenAnswer((_) async => mockBox);
        when(mockBox.put(0, tStoraygeUserModel))
            .thenAnswer((_) async => tStoraygeUserModel);
        // act
        dataSourceImpl.cacheStoraygeUser(tStoraygeUserModel);
        // assert
        verify(mockHiveInterface.openBox(STORAYGE_USER_BOX));
        verify(mockBox.put(STORAYGE_USER_ENTRY, tStoraygeUserModel));
      },
    );
  });

My implementation for dataSourceImpl.cacheStoraygeUser():

@override
  Future<void> cacheStoraygeUser(
      StoraygeUserModel storaygeUserModelToCache) async {
    /// Precaution to ensure that [STORAYGE_USER_BOX] has been opened.
    ///
    /// If the box, is in fact not opened, Hive will just return the box since
    /// the box is a Singleton. I think.
    final box = await hiveInterface.openBox(STORAYGE_USER_BOX);
    box.put(STORAYGE_USER_ENTRY, storaygeUserModelToCache);
  }

When I try to run the test, it gives this error:

type 'Null' is not a subtype of type 'Future<void>'
MockBox.put
package:hive/…/box/box_base.dart:80

I already generated the mock classes for HiveInterface and Box. I think this is how I should do it if I want to test Hive, since I can’t seem to generate Mock classes for Hive itself. But if you know a better or the correct solution then please tell me.

I also wrote another test for getting stuff from Hive. This works perfectly fine.

test(
  'should return StoraygeUser from StoraygeUserBox when there is one in the cache',
  () async {
    // arrange
    when(mockHiveInterface.openBox(any)).thenAnswer((_) async => mockBox);
    when(mockBox.getAt(any)).thenAnswer((_) async => tStoraygeUserModel);
    // act
    final result = await dataSourceImpl.getCachedStoraygeUser();
    // assert
    verify(mockHiveInterface.openBox(any));
    verify(mockBox.getAt(any));
    expect(result, equals(tStoraygeUserModel));
  },
);

Thanks in advance!

Solution

This problem has been fixed in Mockito 5.0.9

The problem stems from the fact that Box implements BoxBase rather than extends it.

Older versions of Mockito couldn’t pick this up and thus, putAt and getAt and other methods are not generated in the mock classes.

Answered By – Nazrin Harris

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *