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

后端 未结 1 1513
一个人的身影
一个人的身影 2021-01-21 01:39

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:

         


        
相关标签:
1条回答
  • 2021-01-21 02:07

    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

    0 讨论(0)
提交回复
热议问题