9
respostas

alguém pode me ajudar com esse erro, o teste não encontra um widget no contactsList

he following TestFailure was thrown running a test:

Expected: <1> Actual: <0> Unexpected number of calls

void main() {
  testWidgets('Shold transfer to a contact', (tester) async {
    final mockContactDao = MocKContactDao();
    await tester.pumpWidget(Bytebank(contactDao: mockContactDao));

    when(mockContactDao.findAll()).thenAnswer((invocation) async {
      //debugPrint('name invocation ${invocation.memberName}');
       return [Contact(0, 'full time', 7000)];
    });
    await clickOnTheTransferFeatureItem (tester);
    await tester.pumpAndSettle();

    final dashboard = find.byType(Dashboard);
    expect(dashboard, findsOneWidget);

    await clickOnTheTransferFeatureItem(tester);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }

    //await tester.pumpAndSettle();

    final contactsList = find.byType(ContactsList);
    //expect(contactsList, findsOneWidget);
    expect(find.text('Transfer', skipOffstage: false), findsNWidgets(1));
    verifyNever(mockContactDao.findAll()).called(1);

     final contactItem = find.byWidgetPredicate((widget) {
  if(widget is ContactItem) {
    return widget.contact.name == 'full time' && widget.contact.accountNumber == 7000;
  }
  return false;
});
expect(contactItem, findsOneWidget);
await tester.tap(contactItem);
await tester.pumpAndSettle();

final transactionForm = find.byType(TransactionForm);
expect(transactionForm, findsOneWidget);
});
}




clickOnTheTransferFeatureItem(WidgetTester tester) {}
9 respostas

Oi Alex tudo bem?

Então, não consegui ter certeza de qual widget não foi encontrado, você pode mandar a exception completa?

esse erro se dar por conta que o teste não encontra o ContactsList em si, porem estou com outro problema no transfer_flow_test.dart

when(mocktransactionwebclient.save(
            Transaction(null, 7000, 'full time'), '1000'))
        .thenAnswer((_) async => Transaction(null, 7000, 'full time'));

o erro está no nome do contato full time que apresenta o erro The argument type 'String' can't be assigned to the parameter type 'Contact?' mesmo eu adicionando o verificador ? na variável ainda apresenta o erro.

aqui está o código completo do tranfer_flow_test.dart

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:newbaytebankproject/lib/lib/components/dialog.dart';
import 'package:newbaytebankproject/lib/lib/components/response_dialog.dart';
import 'package:newbaytebankproject/lib/lib/main.dart';
import 'package:newbaytebankproject/lib/lib/models/contact.dart';
import 'package:newbaytebankproject/lib/lib/models/transaction.dart';
import 'package:newbaytebankproject/lib/lib/screens/contact_list.dart';
import 'package:newbaytebankproject/lib/lib/screens/dashboard.dart';
import 'package:newbaytebankproject/lib/lib/screens/transaction_form.dart';
import 'package:newbaytebankproject/lib/matcher.dart';
import '../mocks/mocks.dart';

void main() {
  testWidgets('Shold transfer to a contact', (tester) async {
    final mockContactDao = MocKContactDao();
    final mocktransactionwebclient = MockTransactionWebClient();
    await tester.pumpWidget(Bytebank(
        transactionWebClient: mocktransactionwebclient,
        contactDao: mockContactDao));
    final Alex = Contact(0, 'full time', 7000);
    when(mockContactDao.findAll()).thenAnswer((invocation) async {
      //debugPrint('name invocation ${invocation.memberName}');
      return [Alex];
    });
    await clickOnTheTransferFeatureItem(tester);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
    //await tester.pumpAndSettle();
    final dashboard = find.byType(Dashboard);
    expect(dashboard, findsOneWidget);
    await clickOnTheTransferFeatureItem(tester);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }

    //await tester.pumpAndSettle();

    //final contactsList = find.byType(ContactsList);
    //expect(contactsList, findsOneWidget);
    expect(find.text('Transfer', skipOffstage: true), findsNWidgets(1));
    verifyNever(mockContactDao.findAll()).called(1);

    final contactItem = find.byWidgetPredicate((widget) {
      if (widget is ContactItem) {
        return widget.contact.name == 'full time' &&
            widget.contact.accountNumber == 7000;
      }
      return false;
    });
    expect(contactItem, findsOneWidget);
    await tester.tap(contactItem);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
//await tester.pumpAndSettle();

    final transactionForm = find.byType(TransactionForm);
    expect(transactionForm, findsOneWidget);

    final contactname = find.text('fulltime');
    expect(contactname, findsOneWidget);
    final accountNumber = find.text('7000');
    expect(accountNumber, findsOneWidget);
    final textfildValue = find.byWidgetPredicate(
        (widget) => textFieldbylabeltextMatcher(widget, 'Value'));
    expect(textfildValue, findsOneWidget);
    await tester.enterText(textfildValue, '200');

    final transferbutton = find.widgetWithText(ElevatedButton, 'Transfer');
    expect(transferbutton, findsOneWidget);
    await tester.tap(transferbutton);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
    final transactionauthdialog = find.byType(TransactionAuthDialog);
    expect(transactionauthdialog, findsOneWidget);

    final textfildpassword = find.byKey(valorDoCampoDaSenhaDeAutenticacaokey);
    expect(textfildpassword, findsOneWidget);
    await tester.enterText(textfildpassword, '1000');

    final canceltbutton = find.widgetWithText(TextButton, 'Cancel');
    expect(canceltbutton, findsOneWidget);

    final comfirmbutton = find.widgetWithText(TextButton, 'Confirm');
    expect(comfirmbutton, findsOneWidget);

    when(mocktransactionwebclient.save(
            Transaction(null, 7000, 'full time'), '1000'))
        .thenAnswer((_) async => Transaction(null, 7000, 'full time'));
    await tester.tap(comfirmbutton);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }

    final successdialog = find.byType(SuccessDialog);
    expect(successdialog, findsOneWidget);

    final okbutton = find.widgetWithText(TextButton, 'oK');
    expect(okbutton, findsOneWidget);
    await tester.tap(okbutton);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
    final contactlistback = find.byType(ContactsList);
    expect(contactlistback, findsOneWidget);
  });
}

clickOnTheTransferFeatureItem(WidgetTester tester) {}

e o contact.dart

class Contact {
  final int? id;
  final String? name;
  final int? accountNumber;

  Contact( this.id, this.name, this.accountNumber,);

  @override
  String toString() {
    return '{Contact{id: $id, name: $name, accountNumber: $accountNumber}';
  }

  Contact.fromJson(Map<String, dynamic> json) :
        id = json['id'],
        name = json['name'],
        accountNumber = json['accountNumber'];

  Map toJson()  { return{
    'id' : id,
    'name': name,
    'accountNumber':accountNumber,};
  }
  @override
bool operator ==(Object other) =>
    identical(this, other) ||
    other is Contact &&
        runtimeType == other.runtimeType &&
        name == other.name &&
        accountNumber == other.accountNumber;

@override
int get hashCode => name.hashCode ^ accountNumber.hashCode;

}

e também o transaction.dart

import 'contact.dart';


class Transaction  {
  final String? id;
  final double value;
  final Contact? contact;

    Transaction(this.id,
    this.value,
    this.contact,
  ):assert(value > 0);

  Transaction.fromJson(Map<String, dynamic> json) :
  id = json['id']?? 0,
  value = json['value'],
  contact = Contact.fromJson(json['contact']?? 0);

  Map<String, dynamic> toJson() => {
    'id': id,
    'value': value,
    'contact': contact?.toJson(),
  };

  @override
  String toString() {
    return 'Transaction{value: $value, contact: $contact}';
  }
  @override
bool operator ==(Object other) =>
    identical(this, other) ||
    other is Transaction &&
        runtimeType == other.runtimeType &&
        value == other.value &&
        contact == other.contact;

@override
int get hashCode => value.hashCode ^ contact.hashCode;
}

quando esse estiver resolvido eu mando a exception do outro erro.

Oi Alex, pelo que eu entendi no seu código:

when(mocktransactionwebclient.save(
            Transaction(null, 7000, 'full time'), '1000'))
        .thenAnswer((_) async => Transaction(null, 7000, 'full time'));

Ele dá o erro: The argument type 'String' can't be assigned to the parameter type 'Contact?'

O que significa que você está colocando uma String, no local que só aceita Contact, dei uma lida no seu código e percebi que:

O Objeto Transaction() precisa de uma String? de um int e de um Contact:

class Transaction  {
  final String? id;
  final double value;
  final Contact? contact;

    Transaction(this.id,
    this.value,
    this.contact,
  ):assert(value > 0);

O que indica que você PRECISA colocar um Contato, e depois ele vai transformar esse contato em uma String por conta própria.

Ou Seja seu codigo precisa ser:

when(mocktransactionwebclient.save(
            Transaction(null, 7000, 'full time'), '1000'))
        .thenAnswer((_) async => Transaction(null, 7000, Contact(id,name,account)));

Quanto ao erro do teste, ele não encontrou o objeto que estava procurando, isso pode se dar por muito motivos: No seu caso ele ta dizendo que esperava que e função findAll() fosse chamada uma vez, mas não foi chamada nenhuma. Você vai precisar dar uma investigada porque o Mock não está chamando a função... pode ser por conta do Stub que você produziu usando o when...

Fico no aguardo pra ver se deu certo!!

Caso este post tenha lhe ajudado, por favor, marcar como solucionado ✓. Bons Estudos!

deu certo a parte do The argument type 'String' can't be assigned to the parameter type 'Contact?'

mas no (save_contact_flow_test) continua dando erro, esse erro ai.

**name invocation Symbol("findAll") ══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════ The following TestFailure was thrown running a test: Expected: exactly one matching node in the widget tree Actual: _WidgetTypeFinder:<zero widgets with type "ContactsList" (ignoring offstage widgets)> Which: means none were found but one was expected

When the exception was thrown, this was the stack:

#4 main. (file:///C:/cursodialog/cursodialog/test/flows/save_contact_flow_test.dart:75:7) (elided one frame from package:stack_trace)

This was caught by the test expectation on the following line: file:///C:/cursodialog/cursodialog/test/flows/save_contact_flow_test.dart line 75 The test description was: Should save a contact **

o codigo do (save_contact_flow_test)

import 'package:flutter/material.dart;
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:newbaytebankproject/lib/lib/http/webClients/transaction_webClient.dart';
import 'package:newbaytebankproject/lib/lib/main.dart';
import 'package:newbaytebankproject/lib/lib/models/contact.dart';
import 'package:newbaytebankproject/lib/lib/screens/contact_form.dart';
import 'package:newbaytebankproject/lib/lib/screens/contact_list.dart';
import 'package:newbaytebankproject/lib/lib/screens/dashboard.dart';
import 'package:newbaytebankproject/lib/matcher.dart';
import '../mocks/mocks.dart;

void main() {
  testWidgets('Should save a contact, (tester) async {
    final mockContactDao = MocKContactDao();
    final transactionWebClient = TransactionWebClient();
    await tester.pumpWidget(Bytebank(
      contactDao: mockContactDao,
      transactionWebClient: transactionWebClient,
    ));
    //await tester.pumpWidget(Bytebank(contactDao: mockContactDao));
    final dashboard = find.byType(Dashboard);
    expect(dashboard, findsOneWidget);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));

      when(mockContactDao.findAll()).thenAnswer((invocation) async {
        debugPrint('name invocation ${invocation.memberName}');
        return [Contact(0, 'full time', 7000)];
      });

      final transferFeatureItem = find.byWidgetPredicate((widget) =>
          featureItemMatcher(widget, 'Transfer', Icons.monetization_on));
      expect(transferFeatureItem, findsOneWidget);
      await tester.tap(transferFeatureItem);
      for (int i = 0; i < 5; i++) {
        await tester.pump(Duration(seconds: 1));
      }

      //await tester.pumpAndSettle();

      final contactsList = find.byType(ContactsList);
      expect(contactsList, findsOneWidget);
      verify(mockContactDao.findAll()).called(1);

      final fabnewContact =
          find.widgetWithIcon(FloatingActionButton, Icons.add);
      expect(fabnewContact, findsOneWidget);
      await tester.tap(fabnewContact);
      for (int i = 0; i < 5; i++) {
        await tester.pump(Duration(seconds: 1));
      }
      //await tester.pumpAndSettle();

      final contactForm = find.byType(ContactForm);
      expect(contactForm, findsOneWidget);
      final nameTextField = find.byWidgetPredicate(
          (widget) => textFieldbylabeltextMatcher(widget, 'Full name'));
      expect(nameTextField, findsOneWidget);
      await tester.enterText(nameTextField, 'ful time');

      final accountNumberTextField = find.byWidgetPredicate(
          (widget) => textFieldbylabeltextMatcher(widget, 'Account number'));
      expect(accountNumberTextField, findsOneWidget);
      await tester.enterText(accountNumberTextField, '7000');

      final createdButton = find.widgetWithText(ElevatedButton, 'Create');
      expect(createdButton, findsOneWidget);
      await tester.tap(createdButton);
      verifyNever(mockContactDao.save(Contact(0, 'full time', 7000)));

      final contactListBack = find.byType(ContactsList);
      expect(contactListBack, findsOneWidget);
      verifyNever(mockContactDao.findAll()).called(1);
    }
  });
}`

o erro fala que esta nessa linha expect(contactListBack, findsOneWidget); no final contactListBack.

e quando comento esse erro aparece outro expect(transferFeatureItem, findsOneWidget);no final transferFeatureItem.

pode me ajudar?

no (transaction-flow_test) ainda esta com o mesmo erro.

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════

The following TestFailure was thrown running a test:

Expected: <1>

Actual: <0>

Unexpected number of calls

#

When the exception was thrown, this was the stack:

#0 fail (package:test_api/src/expect/expect.dart:137:31)

#1 expect (package:testapi/src/expect/expect.dart:132:3)

#2 expect (package:test_api/src/expect/expect.dart:46:3)

#3 VerificationResult.called (package:mockito/src/mock.dart:912:5)

#4 main. (file:///C:/cursodialog/cursodialog/test/flows/transfer_flow_test.dart:44:43)

(elided one frame from package:stack_trace)

The test description was:

Should transfer to a contact

# ai esta o codigo  `transaction-flow_test`
void main() {
  testWidgets('Should transfer to a contact', (tester) async {
    final mockContactDao = MocKContactDao();
    final mocktransactionwebclient = MockTransactionWebClient();
    await tester.pumpWidget(Bytebank(
        transactionWebClient: mocktransactionwebclient,
        contactDao: mockContactDao));
    final Alex = Contact(0, 'full time', 7000);
    when(mockContactDao.findAll()).thenAnswer((invocation) async {
      //debugPrint('name invocation ${invocation.memberName}');
      return [Alex];
    });
    await clickOnTheTransferFeatureItem(tester);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
    //await tester.pumpAndSettle();
    final dashboard = find.byType(Dashboard);
    expect(dashboard, findsOneWidget);
    await clickOnTheTransferFeatureItem(tester);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }

    //await tester.pumpAndSettle();

    final contactsList = find.byType(ContactsList);
    expect(contactsList, findsOneWidget);
    expect(find.text('Transfer', skipOffstage: true), findsNWidgets(1));
    verifyNever(mockContactDao.findAll()).called(1);

    final contactItem = find.byWidgetPredicate((widget) {
      if (widget is ContactItem) {
        return widget.contact.name == 'full time' &&
            widget.contact.accountNumber == 7000;
      }
      return false;
    });
    expect(contactItem, findsOneWidget);
    await tester.tap(contactItem);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
//await tester.pumpAndSettle();

    final transactionForm = find.byType(TransactionForm);
    expect(transactionForm, findsOneWidget);

    final contactname = find.text('fulltime');
    expect(contactname, findsOneWidget);
    final accountNumber = find.text('7000');
    expect(accountNumber, findsOneWidget);
    final textfildValue = find.byWidgetPredicate(
        (widget) => textFieldbylabeltextMatcher(widget, 'Value'));
    expect(textfildValue, findsOneWidget);
    await tester.enterText(textfildValue, '200');

    final transferbutton = find.widgetWithText(ElevatedButton, 'Transfer');
    expect(transferbutton, findsOneWidget);
    await tester.tap(transferbutton);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
    final transactionauthdialog = find.byType(TransactionAuthDialog);
    expect(transactionauthdialog, findsOneWidget);

    final textfildpassword = find.byKey(valorDoCampoDaSenhaDeAutenticacaokey);
    expect(textfildpassword, findsOneWidget);
    await tester.enterText(textfildpassword, '1000');

    final canceltbutton = find.widgetWithText(TextButton, 'Cancel');
    expect(canceltbutton, findsOneWidget);

    final comfirmbutton = find.widgetWithText(TextButton, 'Confirm');
    expect(comfirmbutton, findsOneWidget);

    when(mocktransactionwebclient.save(
            Transaction(null, 7000, Contact(null,'full time', 7000)), '1000'))
        .thenAnswer((_) async => Transaction(null, 7000, Contact(null,'full time', 7000)));
    await tester.tap(comfirmbutton);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }

    final successdialog = find.byType(SuccessDialog);
    expect(successdialog, findsOneWidget);

    final okbutton = find.widgetWithText(TextButton, 'oK');
    expect(okbutton, findsOneWidget);
    await tester.tap(okbutton);
    for (int i = 0; i < 5; i++) {
      await tester.pump(Duration(seconds: 1));
    }
    final contactlistback = find.byType(ContactsList);
    expect(contactlistback, findsOneWidget);
  });
}

clickOnTheTransferFeatureItem(WidgetTester tester) {}

#na video aula o codigo funciona, mas na pratica...!

Então, pelo que eu consegui entender, você chamou a função

verifyNever(mockContactDao.findAll()).called(1);

Que indica que o mockContactDao.findAll() não sera chaamdo NUNCa com esses parametros.

experimenta trocar pra verify(mockContactDao.findAll()).called(1)!