Assertions in Dart and Flutter tests: golden matchers

This is the part of the ultimate cheat sheet dedicated to:

  • image file matcher,
  • image object matcher.

In this series:

Image file matcher

The matchesGoldenFile matcher allows validating that a Finder, Future<ui.Image>, or ui.Image matches the reference (golden) image file:

testWidgets('expectLater: matchesGoldenFile βœ…', (tester) async {
final widget = Container(
width: 200, height: 200,
padding: EdgeInsets.all(20),
color: Colors.white,
child: ColoredBox(color: Colors.blue),
);
await tester.pumpWidget(widget);
await expectLater(find.byType(Container), matchesGoldenFile('golden_test.png'));
});

Image object matcher

The matchesReferenceImage matcher allows validating that a Finder, Future<ui.Image>, or ui.Image matches the reference ui.Image object:

import 'dart:ui' as ui;

testWidgets('expectLater: matchesReferenceImage βœ…', (tester) async {
final key = UniqueKey();
final widget = Container(
width: 200, height: 200,
padding: EdgeInsets.all(20),
child: ColoredBox(color: Colors.green),
);
final image = await createTestImage();
await tester.pumpWidget(
Center(
child: RepaintBoundary(
key: key,
child: widget,
),
),
);
await expectLater(find.byKey(key), matchesReferenceImage(image));
});

Future<ui.Image> createTestImage() {
final paint = ui.Paint()
..style = ui.PaintingStyle.fill
..color = Colors.green;
final recorder = ui.PictureRecorder();
final pictureCanvas = ui.Canvas(recorder);
pictureCanvas.drawRect(Rect.fromLTWH(20, 20, 160, 160), paint);
final picture = recorder.endRecording();
return picture.toImage(200, 200);
}

For testing a Finder, as in the test above, it must match exactly one widget, and the rendered image of the first RepaintBoundary ancestor of the widget is treated as the image for the widget.

Originally published at Invertase blog. Check out their awesome Authors Program!

Hi! πŸ‘‹πŸ» I’m Anna, Google Developer Expert in Flutter from Ukraine πŸ‡ΊπŸ‡¦ Follow me on Twitter, GitHub, YouTube, Medium to get notifications about my latest work.

It’s early 2023, and we in Ukraine are still fighting against russians committing genocide on our lands. If you find this content useful and have a coin to spare, support us with your donations. Stand with Ukraine!

--

--

Anna Leushchenko πŸ‘©β€πŸ’»πŸ’™πŸ“±πŸ‡ΊπŸ‡¦

Google Developer Expert in Dart and Flutter | Author, speaker at tech events, mentor, OSS contributor | Passionate mobile apps creator