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

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

问题描述

我想弄清楚如何为Flutter和Dart的单元测试修改静态吸气剂的返回值。

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

我想修改一个类的静态获取方法的返回值:我想调整不同测试案例的 Platform.isIOS Platform.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.

请注意,我知道此问题的解决方法,例如,我可以将函数拆分为两个函数(每个平台一个),可以注入自己的<$ c $代表受支持平台的c> 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

您还可以使用onPlatform属性为平台创建不同的测试of test()
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中模拟静态获取器的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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