Home > Mobile >  How to unit test my service without passing in Dio object as argument?
How to unit test my service without passing in Dio object as argument?

Time:09-02

I am trying to create wrapper (SDK) below, and the code okay, but when I want to unit test using Mockito I have problem, because in order to use I need to pass in MockDio as an argument, and this can be the problem because I don't want user to specifying dependencies and import Dio package in order to use my package.

class SampleService {
  final String url;
  final String apiKey;
  final Dio dio;

  SampleService({required this.url, required this.apiKey})
      : dio = Dio(BaseOptions(
            baseUrl: url,
            contentType: 'application/json',
            headers: {'API-Key': apiKey}));

  Future<Bitcoin> getTransactionById(String id) async {
    try {
      return await SampleClient(dio).getTransaction(id);
    } catch (obj) {
      throw Exception().throwException(obj);
    }
  }
}

How can I solve the problem

CodePudding user response:

Not sure I understand you, but how about something like this? Then you can mock it for testing, and still not require the users to inject an instance of Dio:

class SampleService {
  final String url;
  final String apiKey;
  late final Dio? dio;

  SampleService({required this.url, required this.apiKey, this.dio}) {
    dio ??= Dio(BaseOptions(
            baseUrl: url,
            contentType: 'application/json',
            headers: {'API-Key': apiKey}));
  }

  ...
}
  • Related