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:
- expect and matcher
- equality matchers
- type and error matchers
- collection matchers
- numeric and comparable matchers
- universal and custom matchers
- matcher operators
- asynchronous expect and matchers
- Flutter widget matchers
- accessibility matchers
- golden matchers
- mock invocations and parameters
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!