Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a method that uses package_info in Flutter?

I am writing a Flutter plugin that checks the Play Store or App Store to see if the app needs to be updated. I'm using the package_info package to determine the version of the app that the user has. My code looks like this:

getVersionStatus() {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    localVersion = packageInfo.version;
    ...
}

I want to test this method, but if it run it as a unit test the fromPlatform call just hangs and times out the test. Is there a more elegant way to solve this than passing in a testing boolean? I.e:

if (testing) {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    localVersion = packageInfo.version;
} else {
    localVersion = '0.0.0'
}

Should the package_info package provide a way to catch errors? Is there a way to tell if the method is being run by a test?

like image 374
Tim Traversy Avatar asked Jan 12 '19 18:01

Tim Traversy


People also ask

How do I test model class in flutter?

Run Flutter test in the terminal, or if you are using Visual Studio Code, press Run ▸ Debug just above the start of the test closure to run the test. You'll see this: 00:02 +2: All tests passed!

How do I use package info plus?

You can use package_info_plus to get the info like the below. import 'package:package_info_plus/package_info_plus. dart'; PackageInfo packageInfo = await PackageInfo. fromPlatform(); String appName = packageInfo.


2 Answers

Like Günter said, you can mock PackageInfo by installing a mock method handler in the MethodChannel for the plugin:

void packageInfoMock() {
  const MethodChannel('plugins.flutter.io/package_info').setMockMethodCallHandler((MethodCall methodCall) async {
    if (methodCall.method == 'getAll') {
      return <String, dynamic>{
        'appName': 'ABC',  // <--- set initial values here
        'packageName': 'A.B.C',  // <--- set initial values here
        'version': '1.0.0',  // <--- set initial values here
        'buildNumber': ''  // <--- set initial values here
      };
    }
    return null;
  });
}
like image 141
silvaric Avatar answered Sep 21 '22 02:09

silvaric


PackageInfo.setMockInitialValues(appName: "abc", packageName: "com.getwedge.wedge", version: "1.0", buildNumber: "2", buildSignature: "buildSignature");
like image 34
Mohamed Inshaf Avatar answered Sep 19 '22 02:09

Mohamed Inshaf