Pris0n
Pris0n

Reputation: 350

Unit Testing hive abstraction layer

So I created a simpler level of abstraction to use Hive into my Flutter app. This should be the central point, where all hive boxes are administrated and accessed. Since e.g. getApplicationDocumentsDirectory is not available during testing, how can I still manage to test this whole file?

import '../services/workout.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_rovider;

import 'workout.dart';

class HiveService {
  static final HiveService _singleton = HiveService._internal();

  static const String _workoutBox = "workoutBox";

  factory HiveService() {
    return _singleton;
  }
  HiveService._internal();

  static Future<void> init() async {
    final appDocumentDirectory =
        await path_rovider.getApplicationDocumentsDirectory();
    Hive.init(appDocumentDirectory.path);
    Hive.registerAdapter(WorkoutAdapter());
  }

  static Future openWorkouts() {
    return Hive.openBox<Workout>(_workoutBox);
  }

  static Future close() {
    return Hive.close();
  }
  
}

Upvotes: 4

Views: 2166

Answers (1)

Abdelazeem Kuratem
Abdelazeem Kuratem

Reputation: 1706

First thing first, you need to initial Hive at the top of the main method in your test file, and then you can proceed with the rest of the tests.

You can use it in this way:

void initHive() {
  var path = Directory.current.path;
  Hive.init(path + '/test/hive_testing_path');
}

main() {
  initHive();
//The rest of your test code.
}

Upvotes: 5

Related Questions