3

I need the screen in the test to look the same as on the physical device(or simulator). How can I do it? In my case device id Iphone SE.

I wrote a test that saves a screenshot to disk:

    testWidgets('test', (WidgetTester tester) async {
  final AutomatedTestWidgetsFlutterBinding binding = tester.binding;
  binding.renderView.configuration = TestViewConfiguration(size: Size(640, 1136));
  var widget = Scaffold(
    appBar: AppBar(title: Text('title'),),
    body: Column(children: <Widget>[
      RaisedButton(
        child: Text('button'),
        onPressed: () {},)
    ],),
  );

  var key = new GlobalKey();
  await tester.pumpWidget(
      MaterialApp(home: RepaintBoundary(key: key, child: widget),),
  );

  await tester.pumpAndSettle();
  await tester.runAsync(() async {
    RenderRepaintBoundary boundary = key.currentContext.findRenderObject();
    var image = await boundary.toImage();
    var byteData = await image.toByteData(format: ImageByteFormat.png);
    var pngBytes = byteData.buffer.asUint8List();
    await File('screen.png').writeAsBytes(pngBytes);
  });
});

if use ViewConfiguration with devicePixelRatio instead TestViewConfiguration, devicePixelRatio ignoring

MediaQuery too don work, if wrap MaterialApp

appbar and button less then on simulator

screen from test: screen from test

but expected(widgets scale): simulator screen

Ivan
  • 256
  • 3
  • 13

1 Answers1

1

You get the blocks instead of text because Flutter uses a specific test font (Ahem) that has all characters just blocks.
This makes it easier to render them equally on Linux (CI) and other platforms. I don't know if there are other reasons.

I also wasn't able to make images work in golden tests.

https://github.com/flutter/engine/pull/6913 was a recently merged fix to allow loading custom fonts in tests.

You can use flutter run --use-test-fonts to make Flutter use the Ahem font when you run the app on a real device so you can visualize how the test will look.

Related issues

I don't know if font's loaded this way work in golden tests though (they might still not work similar to images)

If you want to specify different screen sizes see (not tested myself) How to test Flutter widgets on different screen sizes?

Not sure if this suggestion is still of any value. I found it quite limited and the above suggestion probably works better) In Flutter Widget testing, how to make media.orientation to portrait?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567