Finders e Matchers | Test | Flutter
- Finders e Matchers | Test | Flutter
🧩 1. FINDERS
Os Finders são usados para localizar widgets dentro da árvore de renderização durante os testes.
Todos vêm da classe CommonFinders, acessível via o objeto global find.
📦 Import necessário:
import 'package:flutter_test/flutter_test.dart';
📚 Tabela completa de Finders
| Finder | Descrição | Exemplo |
|---|---|---|
find.text(String text) | Encontra widgets do tipo Text com o texto exato especificado. | find.text('Olá Mundo') |
find.textContaining(String substring) | Encontra textos que contêm o trecho indicado (não precisa ser igual). | find.textContaining('Olá') |
find.byType(Type type) | Encontra todos os widgets de um tipo específico (ex: Icon, TextField). | find.byType(Icon) |
find.byKey(Key key) | Encontra o widget que possui uma Key específica. | find.byKey(const Key('botaoLogin')) |
find.byIcon(IconData icon) | Encontra Icon widgets com um ícone específico. | find.byIcon(Icons.add) |
find.byTooltip(String message) | Encontra widgets com um Tooltip contendo a mensagem especificada. | find.byTooltip('Ajuda') |
find.byWidget(Widget widget) | Encontra um widget específico em memória (comparação de instância). | find.byWidget(const Text('Exemplo')) |
find.byWidgetPredicate(bool Function(Widget widget) test, {String? description}) | Encontra widgets que satisfaçam uma condição personalizada. | find.byWidgetPredicate((w) => w is Text && w.data!.startsWith('Olá')) |
find.descendant({required Finder of, required Finder matching}) | Encontra widgets filhos de um outro widget. | find.descendant(of: find.byType(Column), matching: find.byType(Text)) |
find.ancestor({required Finder of, required Finder matching}) | Encontra widgets pais (ancestrais) de outro widget. | find.ancestor(of: find.text('Login'), matching: find.byType(ElevatedButton)) |
find.bySemanticsLabel(String label) | Encontra widgets acessíveis com uma label específica. | find.bySemanticsLabel('Enviar') |
find.byElementPredicate(bool Function(Element element) test) | Permite filtrar widgets diretamente por elementos da árvore renderizada. | find.byElementPredicate((e) => e.widget is Text) |
find.bySubtype<T>() | Encontra widgets de uma subclasse específica. | find.bySubtype<MyCustomButton>() (Flutter >=3.10) |
🔍 Exemplos práticos
expect(find.text('Login'), findsOneWidget);
expect(find.byType(TextField), findsNWidgets(2));
expect(find.byTooltip('Ajuda'), findsOneWidget);
expect(find.descendant(of: find.byType(Form), matching: find.byType(TextField)), findsWidgets);
🧠 2. MATCHERS
Os Matchers são usados com expect() para verificar quantos widgets foram encontrados ou qual é o resultado esperado.
📦 Import:
import 'package:flutter_test/flutter_test.dart';
🎯 Matchers de quantidade de widgets
| Matcher | Descrição | Exemplo |
|---|---|---|
findsNothing | Nenhum widget encontrado. | expect(find.text('Erro'), findsNothing); |
findsOneWidget | Exatamente um widget encontrado. | expect(find.byIcon(Icons.add), findsOneWidget); |
findsWidgets | Um ou mais widgets encontrados. | expect(find.byType(Text), findsWidgets); |
findsNWidgets(int n) | Exatamente n widgets encontrados. | expect(find.byType(Icon), findsNWidgets(3)); |
✅ Matchers de valores e estados
Esses vêm do pacote package:test (usado internamente pelo Flutter):
| Matcher | Descrição | Exemplo |
|---|---|---|
equals(value) | Verifica igualdade exata. | expect(valor, equals(42)); |
isTrue / isFalse | Verifica valores booleanos. | expect(botaoAtivo, isTrue); |
isNull / isNotNull | Verifica se algo é nulo ou não. | expect(obj, isNotNull); |
contains(value) | Verifica se uma lista ou string contém um valor. | expect(lista, contains('item1')); |
greaterThan(n) / lessThan(n) | Comparações numéricas. | expect(contador, greaterThan(0)); |
throwsException / throwsA(TypeMatcher) | Verifica se uma função lança exceção. | expect(() => funcErro(), throwsException); |
predicate(Function test) | Cria matchers personalizados. | expect(valor, predicate((x) => x > 5)); |
🧩 Exemplo de uso combinado
testWidgets('Exemplo de uso de finders e matchers', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Column(
children: [
Text('Olá Mundo'),
Icon(Icons.add),
Icon(Icons.add),
],
),
),
),
);
expect(find.text('Olá Mundo'), findsOneWidget); // Um texto
expect(find.byType(Icon), findsNWidgets(2)); // Dois ícones
expect(find.text('Tchau'), findsNothing); // Nenhum widget com esse texto
});
🧰 3. Combinações úteis (Finders + Matchers)
| Situação | Código de exemplo |
|---|---|
| Verificar se botão existe | expect(find.byType(ElevatedButton), findsOneWidget); |
| Verificar se texto é renderizado | expect(find.text('Bem-vindo'), findsOneWidget); |
| Verificar ausência de erro | expect(find.text('Erro'), findsNothing); |
| Verificar múltiplos widgets | expect(find.byType(Icon), findsWidgets); |
| Verificar filhos dentro de widget | expect(find.descendant(of: find.byType(Row), matching: find.byType(Text)), findsNWidgets(3)); |
📚 4. Referências oficiais
- 🔗 Flutter Docs – Widget Testing
- 🔗 API Reference – flutter_test
- 🔗 CommonFinders Class Reference
- 🔗 Matchers Reference
🧾 Resumo visual
┌────────────────────────────┐
│ finders │
├────────────────────────────┤
│ find.text('...') │
│ find.byType(WidgetType) │
│ find.byIcon(Icons.add) │
│ find.byKey(Key('...')) │
│ find.descendant(...) │
│ find.ancestor(...) │
└────────────────────────────┘
│
▼
┌────────────────────────────┐
│ matchers │
├────────────────────────────┤
│ findsNothing │
│ findsOneWidget │
│ findsWidgets │
│ findsNWidgets(3) │
└────────────────────────────┘