The non-nullable local variable 'mockLoginRespository' must be assigned before it can be used

35 Views Asked by At

I am trying to develop my app using Clean TDD (Test Driven Development) Architecture. For the login feature , I am writing the test case as follows:

import 'package:dartz/dartz.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:test_app/features/login/domain/entities/user.dart';
import 'package:test_app/features/login/domain/repositories/login_repository.dart';
import 'package:test_app/features/login/domain/usecases/call_login.dart';

class MockLoginRespository extends Mock implements LoginRepository {}

void main() {
  CallLogin usecase;
  MockLoginRespository mockLoginRespository;
  final tUserName = "test.user";
  final tPassword = "test.password";
  final tUser = User(
      userID: "test.userID", email: "test.email", userName: "test.userName");
  setUp(() {
    mockLoginRespository = MockLoginRespository();
    usecase = CallLogin(mockLoginRespository);
  });

  test(
    'should perform login from the repository',
    () async {
      when(mockLoginRespository.login(any, any))
          .thenAnswer((_) async => Right(tUser));

      final result =
          await usecase.execute(username: tUserName, password: tPassword);

      expect(result, Right(tUser));
      verify(mockLoginRespository.login(tUserName, tPassword));
      verifyNoMoreInteractions(mockLoginRespository);
    },
  );
}

I am getting error as :

The non-nullable local variable 'mockLoginRespository' must be assigned before it can be used. Try giving it an initializer expression, or ensure that it's assigned on every execution path.

How should I properly initialize the mockLoginRepository?

I tried adding the initialization expression inside the test async function.

  test(
    'should perform login from the repository',
    () async {

  // Added initialization down here

    mockLoginRespository = MockLoginRespository();
    usecase = CallLogin(mockLoginRespository);
      when(mockLoginRespository.login(any, any))
          .thenAnswer((_) async => Right(tUser));
    .
    .
    .
    },`

This removes the error, but is it the right way to do it ? The code tutorial I follow doesn't make the initialization this way.

0

There are 0 best solutions below