How to mock Platform on Flutter unit tests

Viewed 391

I'm struggling with testing if "platform.isAndroid" in my unit tests. I understand that platform from dart.io cannot be mocked, since it's an abstract instante. However, there's a platform package from google team itself, but unfortunately with no documentation whatsoever or a simple usage example.

Can anyone help with a test example to check if (platform.isAndroid) or iOS ?

I tried mocking it with Mockito, but it didn't work.

import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:platform/platform.dart';

class MyPlatform extends Mock implements LocalPlatform {};

void main() {
    var _platform = MyPlatform();
    when(_platform.isAndroid).thenReturn(true);

    ...

}

My controller is something like the below. I didn't put the whole code due to copyrights reasons, but let me know if you need more details.

import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:platform/platform.dart';
import 'package:share_extend/share_extend.dart';

part 'pdf_view_controller.g.dart';

class PdfViewController = _PdfViewControllerBase with _$PdfViewController;

abstract class _PdfViewControllerBase with Store {
  final _platform = LocalPlatform();

  @observable
  Widget actionButton = SizedBox();

  @action
  getActionButton() async {
    if (_platform.isAndroid) {
      var info = await DeviceInfoPlugin().androidInfo;
      if (info.version.sdkInt < 23) {
        actionButton = SizedBox();
      } else {
        actionButton = IconButton(
          icon: Icon(Icons.share),
          onPressed: () {
            ShareExtend.share(path, "file");
          },
        );
      }
    } else {
      actionButton = IconButton(
        icon: Icon(Icons.share),
        onPressed: () {
          ShareExtend.share(path, "file");
        },
      );
    }
  }
}
0 Answers
Related