【发布时间】:2019-04-29 21:22:00
【问题描述】:
我有一个 StatefulWidget,它在其 initState() 中进行异步调用,以构建一个 Widget。当我手动运行它时,小部件会快速构建。
但是,在我的测试中,即使我使用 await tester.pump() 或 await tester.pumpAndSettle(),小部件似乎也没有构建,直到测试运行之后。
小部件代码:
Widget _coolWidget;
@override
void initState() {
super.initState();
_coolWidget = Container(); // If I set this to OverflowBox() my test passes
_buildWidgetFromCanvas();
}
Future<void> _buildWidgetFromCanvas() {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final ui.Canvas canvas = ui.Canvas(recorder);
// ... more canvas drawing code ...
final img = ... // Image.memory() I build from the canvas
if (!mounted) {
print('no longer mounted');
return;
}
setState(() {
print(img);
_coolWidget = OverflowBox(
child: img,
);
print(_coolWidget);
});
}
测试代码:
void main() {
testWidgets('''OverflowBox shows up.''', (WidgetTester tester) async {
await _setUp(tester); // Just instantiates my widget in an app
await tester.pumpAndSettle();
expect(find.byType(OverflowBox).evaluate().length, 1);
});
}
我在以下位置运行测试结果时的输出:
failed: Error caught by Flutter test framework, thrown running a test.
Expected: <1>
Actual: <0>
但如果我在initState() 中设置_coolWidget = OverflowBox();,则测试通过。
我还有其他在此之后运行的测试。完成这些之后,我看到打印从上方记录了print(img); 和print(_coolWidget);,它正确记录了绘制的图像。
我也得到了 no longer mounted 打印,但这只是在 Flutter 内置 (tearDownAll) 之前的最后一次打印。
在 pump() 和 pumpAndSettle() 中设置持续时间似乎没有任何改变。
我可能遗漏了一些明显的东西。
【问题讨论】:
-
可能相关? github.com/flutter/flutter/issues/23179 虽然我没有添加资产,但我想创建一个 png 然后从内存中加载它有点像资产?
标签: asynchronous testing dart flutter