Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a static getter's return value in Dart or Flutter?

Tags:

I would like to figure out how to modify the return value of a static getter for my unit tests in Flutter and Dart.

I'm unit testing a simple function:

  Future<bool> exampleFunc() async {
    if (Platform.isIOS) {
      // Do some iOS-specific things
      return false;
    } else if (Platform.isAndroid) {
      // Do some Android-specific things
      return true; // just as an example
    }
    throw 'Unexpected platform';
  }

And I would like to modify the return values of the static getters of a class: I would like to tweak Platform.isIOS and Platform.isAndroid return value for the different test cases.

Please note that I know of workarounds for this issue, for example, I could split the function into two functions (one for each platform), I could inject my own enum (or in this case, even a bool might work) that represents the supported platforms. In this example, I am actually going to do that, but I would like to know how to "modify" the return values of the Platform class's getters, because sometimes, you don't want to modify the signature of a function, as others might depend on it and yet, you still want to unit test the function.

like image 731
Vince Varga Avatar asked Jan 04 '20 15:01

Vince Varga


1 Answers

You should not mock classes that you don't own. Your unit test must be platform independent. On your case you should refactor your code to get rid of this dependency.

If you really wanna continue with this dependency at least depends on abstractions:

abstract class MyPlatform {
  bool isAndroid();
  bool isIos();
 }

class MyPlatformImp implements MyPlatform {
  @override
  bool isAndroid() => Platform.isAndroid;
  @override
  bool isIos() => Platform.isIOS;
 }

then you can mock MyPlatform on your uses.

This kind of variable you would test on Integration Tests https://flutter.dev/docs/cookbook/testing/integration/introduction

You can also create different tests for platforms using the onPlatform attribute of test() https://api.flutter.dev/flutter/test_api/test.html

like image 163
Jhionan Santos Avatar answered Sep 30 '22 14:09

Jhionan Santos