Mocking Hive with Mockito Flutter


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.


group('cacheStoraygeUser', () {
      '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
        // assert
        verify(mockBox.put(STORAYGE_USER_ENTRY, tStoraygeUserModel));

My implementation for dataSourceImpl.cacheStoraygeUser():

  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>'

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.

  '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
    expect(result, equals(tStoraygeUserModel));

Thanks in advance!


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 *