我有一个Flutter小部件,根据屏幕尺寸显示额外的数据。有人知道在多种不同屏幕尺寸上测试此小部件的方法吗?
我已经浏览了widget_tester源代码,但是找不到任何东西。
答案 0 :(得分:9)
您可以使用TestWidgetsFlutterBinding
指定自定义表面尺寸以下代码将运行屏幕尺寸为42x42的测试
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final TestWidgetsFlutterBinding binding =
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets("foo", (tester) async {
await binding.setSurfaceSize(Size(42, 42));
// TODO: do something
});
}
答案 1 :(得分:5)
有一个名为1的软件包,可以模拟在不同设备上运行的flutter应用。
答案 2 :(得分:1)
不知道为什么,但是@rémi-rousselet的解决方案对我不起作用。我必须使用binding.window.physicalSizeTestValue
和binding.window.devicePixelRatioTestValue
指定屏幕尺寸,以便输出是完全确定的
我为像我这样扑朔迷离的初学者添加了更多代码。检查一下:
void main() {
final TestWidgetsFlutterBinding binding =
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets("Basic layout test (mobile device)", (tester) async {
binding.window.physicalSizeTestValue = Size(400, 200);
binding.window.devicePixelRatioTestValue = 1.0;
await tester.pumpWidget(new MyApp());
expect(find.byType(MyHomePage), findsOneWidget);
// etc.
});
}
答案 3 :(得分:1)
@rémi-rousselet的解决方案效果很好!
此外,如果要测试方向更改,请尝试以下操作:
const double PORTRAIT_WIDTH = 400.0;
const double PORTRAIT_HEIGHT = 800.0;
const double LANDSCAPE_WIDTH = PORTRAIT_HEIGHT;
const double LANDSCAPE_HEIGHT = PORTRAIT_WIDTH;
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
await binding.setSurfaceSize(Size(PORTRAIT_WIDTH, PORTRAIT_HEIGHT));
await tester.pumpWidget(MyWidget());
// test in portrait
await binding.setSurfaceSize(Size(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT));
await tester.pumpAndSettle();
// OrientationBuilder gets triggered
// test in landscape
答案 4 :(得分:1)
您可以尝试使用此小部件来测试您的小部件实时更改屏幕大小
屏幕尺寸测试
https://pub.dev/packages/screen_size_test
预览
演示 https://dartpad.dartlang.org/43d9c47a8bf031ce3ef2f6314c9dbd52
代码示例
import 'package:screen_size_test/screen_size_test.dart';
...
MaterialApp(
title: 'Demo',
builder: (context, child) => ScreenSizeTest(
child: child,
),
home: Scaffold(
body: ListView(
children: List.generate(
20,
(index) => Container(
padding: EdgeInsets.all(10),
child: Placeholder(),
)),
),
),
)
答案 5 :(得分:0)
尽管@RémiRousselet的回答非常有帮助,但并不能完全解决我的问题。事实证明,我可以将待测试的小部件包装在MediaQuery
小部件中并设置大小。
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
Widget makeTestableWidget({Widget child, Size size}) {
return MaterialApp(
home: MediaQuery(
data: MediaQueryData(size: size),
child: child,
),
);
}
testWidgets("tablet", (tester) async {
final testableWidget = makeTestableWidget(
child: WidgetUnderTest(),
size: Size(1024, 768),
);
...
});
testWidgets("phone", (tester) async {
final testableWidget = makeTestableWidget(
child: WidgetUnderTest(),
size: Size(375, 812),
);
...
});
}