What is flutter_test?
- Flutter course
- Advanced
- Lesson 61/69
- 4 min
Start writing widget tests with flutter_test.
What is flutter_test?
The flutter_test package is the official testing framework for Flutter widgets. The testWidgets function sets up a test environment, Finder locates widgets, and expect verifies them. Tests live in the test/ folder with the _test.dart extension.
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows title', (tester) async {
await tester.pumpWidget(MyApp());
expect(find.text('Hello'), findsOneWidget);
});
}Finding widgets with Finder
Finder is used to search the widget tree. find.text matches by text, find.byType by widget type, and find.byKey by key. You check the Finder result with expect against values like findsOneWidget or findsNothing.
Practice First widget test
In main, write a testWidgets test named 'metin gosterilir'. Render MaterialApp(home: Text('Merhaba')) with pumpWidget. Verify with find.text('Merhaba') and findsOneWidget. Finally print 'test tanimlandi'.
Starter code
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';
void main() {
// 'metin gosterilir' adlı bir testWidgets testi yaz
// pumpWidget ile MaterialApp içinde Text render et
// find.text ile metni bul ve tek widget bulunduğunu doğrula
// son olarak 'test tanimlandi' yazdir
}Sample solution
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/material.dart';
void main() {
testWidgets('metin gosterilir', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Text('Merhaba')),
);
expect(find.text('Merhaba'), findsOneWidget);
});
print('test tanimlandi');
}Expected output
test tanimlandi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which folder are test files placed?
- assets/
- test/ Correct answer
- lib/
- bin/
Explanation: Flutter tests live in the test/ folder with the _test.dart extension; the flutter test command scans that folder.
2 Search for text with find
expect(find.____('Merhaba'), findsOneWidget);
expect(find.text('Merhaba'), findsOneWidget);
Explanation: The find.text method finds a widget with the given text in the widget tree; find.byType searches by type, find.byKey by key.
3 flutter_test parts
| Term | Meaning |
|---|---|
flutter_test |
Testing framework |
testWidgets |
Sets up test environment |
Finder |
Widget finding |
expect |
Verification |