如何在 Dart 或 Flutter 中模拟静态 getter 的返回值? [英] How to mock a static getter's return value in Dart or Flutter?

查看:38
本文介绍了如何在 Dart 或 Flutter 中模拟静态 getter 的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何为我在 Flutter 和 Dart 中的单元测试修改静态 getter 的返回值.

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';
  }

我想修改一个类的静态 getter 的返回值:我想调整 Platform.isIOSPlatform.isAndroid 的返回值不同的测试用例.

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.

请注意,我知道此问题的解决方法,例如,我可以将函数拆分为两个函数(每个平台一个),我可以注入自己的 enum(或者在这种情况下,即使是 bool 也可能工作)代表支持的平台.在这个例子中,我实际上打算这样做,但我想知道如何修改" Platform 类的 getter 的返回值,因为有时,您不想修改函数的签名,因为其他人可能会依赖它,但您仍然希望对函数进行单元测试.

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.

推荐答案

你不应该模拟你不拥有的类.您的单元测试必须独立于平台.在您的情况下,您应该重构代码以摆脱这种依赖关系.

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;
 }

然后你可以在你的用途上模拟 MyPlatform.

then you can mock MyPlatform on your uses.

您将在集成测试中测试这种变量https://flutter.dev/docs/cookbook/testing/integration/introduction

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

您还可以使用 test() 的 onPlatform 属性为平台创建不同的测试https://api.flutter.dev/flutter/test_api/test.html

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

这篇关于如何在 Dart 或 Flutter 中模拟静态 getter 的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆