如何使用Widget测试共享包



我在尝试测试Share包时遇到问题。我的代码如下:

IconButton(
key: Key('share-button'),
icon: Icon(Platform.isAndroid ? Icons.share : CupertinoIcons.share),
onPressed: () {
if (activity.shareLink != null) {
Share.share('${activity.shareLink}');
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Request Error'),
),
);
}
},
)

我提供了[activity.shareLink],我的测试看起来像这样:

await tester.tap(find.byKey(Key('share-button')));
await tester.pump(Duration(seconds: 1));
expect(find.byType(Share), findsOneWidget); 

我的例外是:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
Expected: exactly one matching node in the widget tree
Actual: _WidgetTypeFinder:<zero widgets with type "Share" (ignoring offstage widgets)>
Which: means none were found but one was expected

这就是他们在GitHub库中测试包的方式,也许你应该这样测试:

expect(Share.share('message', subject: 'title'), completes);

Github存储库share_plus

与许多使用本机代码的包一样,Share功能的小部件测试依赖于为平台本机部分注入模拟实现。

通常这涉及到";xyz平台";类,该类公开链接到当前平台的实现的静态instance字段。在共享(Plus(的情况下,这将是SharePlatform.instance

以下是使用您最喜欢的模拟库测试此类平台功能调用的常见方法:

  1. 添加包含";平台";接口作为项目的dev依赖项。(惯例是将这样的包命名为"xxx_platform_interface",您可以在Pub.dev中找到该名称作为包的依赖项之一。(
  2. 为适当的"声明一个mock类;平台";使用with MockPlatformInterfaceMixin将其标记为平台接口
  3. 在测试中创建平台mock的实例
  4. 通过将该mock分配给适当的"0"的静态CCD_ 4字段,在测试期间使用该mock作为平台实现;平台";类
  5. 模拟您期望调用的方法的行为(如果必要(
  6. 使用WidgetTester实例执行与适当小部件的交互
  7. 验证是否发生了预期的调用

最新更新