flutter mockito: How to call repository function for testing

Viewed 554

there is no issue in development. this issue is in testing.

Alternative 1

void main() async {
    SoldRepository repository;
  FirebaseFirestore _firestore;

  final sold = Sold(
      buyerDisplayName: UserDisplayNameSold("Saugat Thapa"),
      buyerEmail: EmailAddressBought("saugat26@gmail.com", true),
      buyerPhotoUrl: UserPhotoUrlSold(
          " https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg"),
      buyerUserId: UserIdSold("haSW0s5MxOOENWnc5T1cLinekj2"),
      id: UniqueId(),
      quotations: List3Sold(KtList.of(
        Quotation(
            id: UniqueId(),
            measuremntUnit: QuotationUnit("Kilogram"),
            quantity: QuotationQuantity(10),
            rate: QuotationRate(12),
            title: QuotationTitle("Onion"),
            index: QuotationIndex(8),
            isSelected: QuotationSelected(false)),
      )),
      sellerDisplayName: UserDisplayNameSold("riwat rai"),
      sellerEmail: EmailAddressSold("riwatj@gmail.com"),
      sellerPhotoUrl: UserPhotoUrlSold(
          " https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg"),
      sellerUserId: UserIdSold("DULkECyxWzfBosXXBbOMpfnij1"),
      total: SoldTotalHere(10));
  // User sellerUserDetail;
  final auth = MockFirebaseAuth();
  final googleSignIn = MockGoogleSignIn();
  u.User sellerUserDetail;
  sellerUserDetail = u.User(
      email: "ku1438693@gmail.com",
      photoUrl:
          "https://lh6.googleusercontent.com/-5HXS8qkwKnw/AAAAAAAAAAI/AAAAAAAAAAA/AAKWJJMiRHRadk3nDhlaLa-sU0_fsPrHhQ/photo.jpg",
      id: UniqueId(),
      displayName: "Lila Kunwar");
  setUp(() async {
    repository = SoldRepository(_firestore);
   
  });
  

  test('creates bill in collection sold', () async {
    //arrange
   
    //act

    repository.createTest(sold, sellerUserDetail);
    // assert
    expect(result, right(sold));
  });
}

call repository.createTest(sold, sellerUserDetail) and error arises. i expect problem from FirebaseFirestore _firestore; but how can i overcome the problem.

abstract class ISoldRepository {
  
  Future<Either<SoldFailure, Unit>> createTest(
      Sold sold, User sellerUserDetail);
  
}
/* import 'dart:ui';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:mobile_shamagri_bloc/domain/core/value_objects.dart'; */

import 'dart:developer';

import 'package:cloud_firestore/cloud_firestore.dart';
// import 'package:flutter/services.dart';
import 'package:injectable/injectable.dart';
import 'package:dartz/dartz.dart';
import 'package:kt_dart/kt.dart';
import 'package:logger/logger.dart';
import 'package:mobile_shamagri_bloc/domain/auth/i_auth_facade.dart';
import 'package:mobile_shamagri_bloc/domain/auth/user.dart';
import 'package:mobile_shamagri_bloc/domain/core/errors.dart';
import 'package:mobile_shamagri_bloc/domain/sold/i_sold_repository.dart';
import 'package:mobile_shamagri_bloc/domain/sold/sold_failure.dart';
import 'package:mobile_shamagri_bloc/domain/sold/sold.dart';
import 'package:mobile_shamagri_bloc/domain/sold_not_form/sold_not_form.dart';
import 'package:mobile_shamagri_bloc/domain/sold_not_form/sold_not_form_failure.dart';
import 'package:mobile_shamagri_bloc/infrastructure/core/firestore_helpers.dart';
import 'package:mobile_shamagri_bloc/infrastructure/sold_reso/sold_dtos.dart';
import 'package:mobile_shamagri_bloc/injection.dart';
// import 'package:mobile_shamagri_bloc/infrastructure/sold_reso/sold_dtos.dart';
import 'package:rxdart/rxdart.dart';

@LazySingleton(as: ISoldRepository)
class SoldRepository implements ISoldRepository {
  final FirebaseFirestore _firestore;

  SoldRepository(this._firestore);
  String buyerUserID;
  String buyerDisplayName;
  String buyerPhotoUrl;

  
  Future<Either<SoldFailure, Unit>> createTest(
      Sold sold, User sellerUserDetail) async {
    try {
      final soldDto = SoldDto.fromDomain(
          sold,
          sellerUserDetail,
          sold.buyerUserId.getOrCrash(),
          sold.buyerDisplayName.getOrCrash(),
          sold.buyerPhotoUrl.getOrCrash());

      await _firestore
          .collection("sold")// here is the error
          .doc(soldDto.soldId)
          .collection("invoice")
          .doc()
          .set(soldDto.toJson());

      return right(unit);
    } on FirebaseException catch (e) {
      if (e.message.contains('PERMISSION_DENIED')) {
        return left(const SoldFailure.insufficientPermission());
      } else {
        var logger = Logger();
        logger.wtf("unexpected error " + e.toString());
        return left(const SoldFailure.unexpected());
      }
    }
  }
  

}

how can i not call method 'collection' on null?

creates bill in collection sold [E]
  NoSuchMethodError: The method 'collection' was called on null.
  Receiver: null
  Tried calling: collection("sold")
  dart:core                                                                          Object.noSuchMethod
  package:mobile_shamagri_bloc/infrastructure/sold_reso/sold_repository.dart 228:12  SoldRepository.createTest
  test\features\sold\presentation\bloc\create.dart 85:21                             main.<fn>
  test\features\sold\presentation\bloc\create.dart 83:43                             main.<fn>
  ===== asynchronous gap ===========================
  dart:async                                                                         _completeOnAsyncError
  package:mobile_shamagri_bloc/infrastructure/sold_reso/sold_repository.dart         SoldRepository.createTest
  test\features\sold\presentation\bloc\create.dart 85:21                             main.<fn>
  test\features\sold\presentation\bloc\create.dart 83:43                             main.<fn>

  NoSuchMethodError: The method 'collection' was called on null.
  Receiver: null
  Tried calling: collection("sold")
  dart:core                                                                          Object.noSuchMethod
  package:mobile_shamagri_bloc/infrastructure/sold_reso/sold_repository.dart 228:12  SoldRepository.createTest
  test\features\sold\presentation\bloc\create.dart 88:31                             main.<fn>
  test\features\sold\presentation\bloc\create.dart 83:43                             main.<fn>
  ===== asynchronous gap ===========================
  dart:async                                                                         _completeOnAsyncError
  package:mobile_shamagri_bloc/infrastructure/sold_reso/sold_repository.dart         SoldRepository.createTest
  test\features\sold\presentation\bloc\create.dart 88:31                             main.<fn>
  test\features\sold\presentation\bloc\create.dart 83:43                             main.<fn>

  Expected: Right<dynamic, Sold>:<Right(Sold(id: Value(Right(6f567c00-16a0-11ec-b349-256f5961cbea)), total: Value(Right(10)), buyerEmail: Value(Right(saugat26@gmail.com)), quotations: Value(Right([Quotation(id: Value(Right(6f56ca20-16a0-11ec-8c22-5db758776962)), title: Value(Right(Onion)), measuremntUnit: Value(Right(Kilogram)), rate: Value(Right(12)), quantity: Value(Right(10)), isSelected: Value(Right(false)), index: Value(Right(8)))])), sellerEmail: Value(Right(rrj@gmail.com)), sellerUserId: Value(Right(DULkEuiCyzfBosXXBbOMpfnij1)), buyerUserId: Value(Right(hanSW0s5MxOONWnc5T1cLinekj2)), sellerDisplayName: Value(Right(riwat rai)), buyerDisplayName: Value(Right(Saugat Thapa)), sellerPhotoUrl: Value(Right( https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg)), buyerPhotoUrl: Value(Right( https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg))))>
    Actual: <Instance of 'Future<Either<SoldFailure, Unit>>'>

  package:test_api                                        expect
  package:flutter_test/src/widget_tester.dart 428:3       expect
  test\features\sold\presentation\bloc\create.dart 90:5   main.<fn>
  test\features\sold\presentation\bloc\create.dart 83:43  main.<fn>

Alternative 2

void main() async {
    SoldRepository repository;
  FirebaseFirestore _firestore;

  final sold = Sold(
      buyerDisplayName: UserDisplayNameSold("Saugat Thapa"),
      buyerEmail: EmailAddressBought("saugat26@gmail.com", true),
      buyerPhotoUrl: UserPhotoUrlSold(
          " https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg"),
      buyerUserId: UserIdSold("hanSW0s5MxOOENWnc5T1cLinekj2"),
      id: UniqueId(),
      quotations: List3Sold(KtList.of(
        Quotation(
            id: UniqueId(),
            measuremntUnit: QuotationUnit("Kilogram"),
            quantity: QuotationQuantity(10),
            rate: QuotationRate(12),
            title: QuotationTitle("Onion"),
            index: QuotationIndex(8),
            isSelected: QuotationSelected(false)),
      )),
      sellerDisplayName: UserDisplayNameSold("riwat rai"),
      sellerEmail: EmailAddressSold("riwatj@gmail.com"),
      sellerPhotoUrl: UserPhotoUrlSold(
          " https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg"),
      sellerUserId: UserIdSold("DULkEuiCyxWzfBosXXBbOMpfnij1"),
      total: SoldTotalHere(10));
  // User sellerUserDetail;
  final auth = MockFirebaseAuth();
  final googleSignIn = MockGoogleSignIn();
  u.User sellerUserDetail;
  sellerUserDetail = u.User(
      email: "ku143863@gmail.com",
      photoUrl:
          "https://lh6.googleusercontent.com/-5HXS8qkwKnw/AAAAAAAAAAI/AAAAAAAAAAA/AAKWJJMiRHRadk3nDhlaLa-sU0_fsPrHhQ/photo.jpg",
      id: UniqueId(),
      displayName: "Lila Kunwar");
  setUp(() async {
    repository = SoldRepository(_firestore);
   
  });
  

  test('creates bill in collection sold', () async {
    //arrange
   
    //act

   ISoldRepository repository;
    final globalResult = repository.createTest(sold, sellerUserDetail);
    expect(globalResult, d.right(sold));
  });
}
00:02 +0 -1: creates bill in collection sold [E]
  NoSuchMethodError: The method 'createTest' was called on null.
  Receiver: null
  Tried calling: createTest(Instance of '_$_Sold', Instance of '_$_User')
  dart:core                                               Object.noSuchMethod
  test\features\sold\presentation\bloc\create.dart 88:37  main.<fn>
  test\features\sold\presentation\bloc\create.dart 83:43  main.<fn>
1 Answers
  • In Alternative 1, you're calling .collection on null because the _firestore variable is just declared but not assigned to any value.

  • In Alternative 2, you're calling .createTest on null because the repository variable that is calling .createTest is the one declared in the test method below, and it is null since it is not assigned any value.

    test('creates bill in collection sold', () async {
        ISoldRepository repository;
        final globalResult = repository.createTest(sold, sellerUserDetail);
        expect(globalResult, d.right(sold));
    });
    

You can mock FirebaseFirestore using mockito and assign it to your _firestore variable. Check out this article on how to write unit tests with Firestore.

Related