问题描述
我在尝试测试 Flutter 应用程序时遇到错误。我有一个自定义小部件,它位于 CustomScrollView
小部件的底部(在第一个视口之外)。在我的测试中,我想验证它是否真的存在。
我已经尝试使用 WidgetTester.scrollUntilVisible
和 WidgetTester.drag
(就像在 Flutter 框架的测试中所做的那样)。此外,我尝试使用 FlutterDriver
重构我的测试,这将其他一切都完全搞砸了。
如何滚动到测试中 CustomScrollView
的底部?
这个最小的复制显示了包含 CustomScrollView
的应用程序,它具有一个屏幕高度的容器小部件(因此我想要找到的小部件不在初始视图中)
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Container(
height: MediaQuery.of(context).size.height,),MyWidget(),],)),);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SliverToBoxAdapter(
child: Container(
height: 100,width: 100,);
}
}
这是我最初编写的用于查找小部件的测试,当然失败了。
void main() {
testWidgets('main contains mywidget',(WidgetTester tester) async {
// arange
await tester.pumpWidget(MyApp());
// act
final myWidget = find.byType(MyWidget);
// assert
expect(myWidget,findsOneWidget);
});
}
在本次迭代中,我使用了 WidgetTester.scrollUntilVisible
函数,但出现以下错误。
void main() {
testWidgets('main contains mywidget',(WidgetTester tester) async {
// arange
await tester.pumpWidget(MyApp());
// act
final myWidget = find.byType(MyWidget);
final customScrollView = find.byType(CustomScrollView);
await tester.scrollUntilVisible(myWidget,100,scrollable: customScrollView);
await tester.pump();
// assert
expect(myWidget,findsOneWidget);
});
}
══╡ EXCEPTION CAUGHT BY FlutteR TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following _CastError was thrown running a test:
type 'CustomScrollView' is not a subtype of type 'Scrollable' in type cast
When the exception was thrown,this was the stack:
#0 WidgetController.widget (package:Flutter_test/src/controller.dart:66:44)
#1 WidgetController.scrollUntilVisible.<anonymous closure> (package:Flutter_test/src/controller.dart:995:15)
#2 WidgetController.scrollUntilVisible.<anonymous closure> (package:Flutter_test/src/controller.dart:993:39)
#5 TestAsyncUtils.guard (package:Flutter_test/src/test_async_utils.dart:72:41)
#6 WidgetController.scrollUntilVisible (package:Flutter_test/src/controller.dart:993:27)
#7 main.<anonymous closure> (file:///C:/Users/X/test_example/test/main_test.dart:12:18)
<asynchronous suspension>
<asynchronous suspension>
(elided 3 frames from dart:async and package:stack_trace)
感谢您提供有关如何解决此问题并成功测试我的 CustomScrollView
解决方法
我遇到了同样的问题,最终我使用了 dragUntilVisible() 方法而不是 scrollUntilVisible()。
向下滚动直到小部件可见的示例:
await tester.dragUntilVisible(myWidget,customScrollView,Offset(0,-500));