首页 > 解决方案 > 如何在 Flutter 中测试私有函数/方法?

问题描述

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

所以问题是我如何从文本包中的测试类测试集团的私有方法,这样它就不能访问其他包的私有方法。

谢谢

标签: testingflutter

解决方案


你不能,但你可以将它们公开并注释它,@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.

推荐阅读