Search code examples
flutterunit-testinghive

Flutter hive unit test


I got a problem with testing function calling hive put method, now i'm gonna provide my code for the function, test and the error message

///////////////////// Function impl. ////////////////////////

class AppLocalDataSourceImpl implements AppLocalDataSource {
  static const _kTag = "AppLocalDataSource";
  final Box _appBox;

  AppLocalDataSourceImpl({required Box appBox}) : _appBox = appBox;

  @override
  Future<void> updateAppCountry(CountryModel country) async {
    try {
      await _appBox.put(
        CacheKeys.ckAppCountry,
        country,
      );
    } catch (e) {
      logError("$_kTag updateAppCountry Error: $e");
      throw LocalStorageException(
        errLogMessage: localStorageErrorMessage(e.toString()),
      );
    }
  }
}

//////////////////// Test impl. ////////////////////////

class MockBox extends Mock implements Box<dynamic> {}

void main() {
  group('AppLocalDataSourceImpl Tests', () {
    late AppLocalDataSourceImpl dataSource;
    late MockBox mockBox;

    setUp(() async {
      mockBox = MockBox();
      dataSource = AppLocalDataSourceImpl(appBox: mockBox);
    });

    test('updateAppCountry calls put with correct parameters', () async {
      // Arrange
      const country = CountryModel(
        id: 1,
        icon: 'icon_url',
        name: 'Test Country',
        code: 'TC',
        currency: CurrencyModel(id: 1, currency: 'USD', name: 'US Dollar'),
      );

      when(mockBox.put(any, any)).thenAnswer((inn) async => Future.value());

      // Act
      await dataSource.updateAppCountry(country);

      // Assert
      verify(mockBox.put(CacheKeys.ckAppCountry, country)).called(1);
    });
  });
}

///////////////////////// Error ///////////////////////////

00:02 +6 -1: AppLocalDataSourceImpl Tests updateAppCountry calls put with correct parameters [E]                                                                                                         
  type 'Null' is not a subtype of type 'Future<void>'
  test/src/core/app_data/data_source/local/app_local_data_source_impl_test.dart 11:7    MockBox.put
  test/src/core/app_data/data_source/local/app_local_data_source_impl_test.dart 124:20  main.<fn>.<fn>
  

To run this test again: /Users/macbook/Dev/flutter/bin/cache/dart-sdk/bin/dart test /Users/macbook/StudioProjects/TravelApp/test/src/core/app_data/data_source/local/app_local_data_source_impl_test.dart -p vm --plain-name 'AppLocalDataSourceImpl Tests updateAppCountry calls put with correct parameters'
00:02 +6 -1: Some tests failed. 

Solution

  • when(mockBox.put(any, any)).thenAnswer((inn) async => Future.value());
    

    Here, instead of any put there any().