如何在 Flutter 中测试私有函数/方法?

ont*_*oon 13 testing flutter

我目前正在开发一个使用 bloc 架构的应用程序。我的集团专门使用流与 UI 进行通信。因此,除了构造函数之外,它的所有方法都是私有的(它们以“_”开头)。

所以问题是如何从文本包中的测试类中测试 bloc 的私有方法,使其无法访问其他包的私有方法。

谢谢

Gün*_*uer 14

您不能,但是您可以将它们@visibleForTesting设为公开并使用注释来获得 DartAnalyzer 警告,当从不在同一个库中或不在同一库中的代码访问它们时test/

https://github.com/dart-lang/sdk/blob/master/pkg/meta/lib/meta.dart#L224-L233

/// Used to annotate a declaration was made public, so that it is more visible
/// than otherwise necessary, to make code testable.
///
/// Tools, such as the analyzer, can provide feedback if
///
/// * the annotation is associated with a declaration not in the `lib` folder
///   of a package, or
/// * the declaration is referenced outside of its the defining library or a
///   library which is in the `test` folder of the defining package.
Run Code Online (Sandbox Code Playgroud)

  • 还是应该尽量避免这种情况 (3认同)
  • 这是一个相当哲学的观点。我的答案是关于是否可以或如何完成。其余的不是 Dart/Flutter 特定的。请参阅 /sf/ask/7350521/ (3认同)
  • 您可以从 Flutter 导入它(`package:flutter/foundation.dart` 导出它。)或将 `meta` 包添加到 `pubspec.yaml` 中的 `dependencies:`(并从那里导入)。 (2认同)

Eli*_*rov 5

我现在解决了这个问题,方法是使用相同的参数创建另一个公共“存根”方法,该方法仅调用私有方法并将其标记为@visibleForTesting. 这

@visibleForTesting
  Future<void> removeAppointments(List<DocumentSnapshot> documents, [FirebaseFirestore instance]) => _removeAppointments(documents, instance);
Run Code Online (Sandbox Code Playgroud)