Quick Introduction to Tests in Flutter

Environment Setup

sdk: flutter
sdk: flutter

Folder Structure


Test Types

Unit Test

Widget Test

Integration Test

Golden Test

Photo : Official Flutter documentation

Implementing Unit Test

class PrintTest{ String test  = ‘Test’;
String test2 = ‘Test2’;
String printTest(){ return test;
String printTest2(){ return test;
import ‘package:app/printTest.dart’;import ‘package:flutter_test/flutter_test.dart’;void main(){ test(‘test variable should be printed’,(){   final PrintTest printTest = PrintTest();   expect(printTest.printTest(), ‘test’); });}
flutter test test/{file name}.dart

Implementing Widget Test

class CustomWidget extends StatelessWidget {
const CustomWidget({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘Test Widget’),
leading: IconButton(
icon: Icon(Icons.play_arrow),
onPressed: () {
print(‘Pressed Icon’);
body: Container(),
find.text('{type the text you are looking for}’) = If you want to find a text widget in the test environment you can use this function.
find.byWidget(widget instance name) = This function finds a specific instance of a widget
findsOneWidget : This matcher locates only one widget in the tree. findsNothing : Verifies that no widgets are found.
void main() {  testWidgets(‘CustomWidget is working expected’, (WidgetTester 
tester) async {
// Build our app and trigger a frame. await tester.pumpWidget(const MyApp());
// Verify that our appbar has ‘Test Widget’ text. expect(find.text(‘Test Widget’), findsOneWidget);
// Tap the icon await tester.tap(find.byIcon(Icons.play_arrow));
//trigger a frame. await tester.pump(); });}
void main() {
testWidgets(‘Counter increments smoke test’, (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp(
items: List<String>.generate(10000, (i) => “Item $i”),
final listFinder = find.byType(Scrollable);
final itemFinder = find.byKey(const ValueKey(‘item_50_text’));
// Scroll until the item to be found appears.
await tester.scrollUntilVisible(
scrollable: listFinder,
// Verify that the item contains the correct text.
expect(itemFinder, findsOneWidget);

Implementing Integration Test

void main() {
group(‘end-to-end test’, () {
testWidgets(‘tap on the floating action button, verify counter’,
(WidgetTester tester) async {
await tester.pumpAndSettle();
// Verify the counter starts at 0.
expect(find.text(‘0’), findsOneWidget);
// Finds the floating action button to tap on.
final Finder fab = find.byTooltip(‘Increment’);
// Emulate a tap on the floating action button.
await tester.tap(fab);
// Trigger a frame.
await tester.pumpAndSettle();
// Verify the counter increments by 1.
expect(find.text(‘1’), findsOneWidget);



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store