non-null variable in flutter test
Asked Answered
C

2

5

I was learning flutter about year ago and now im coming back after a break but i counter a problem, it's probalby pretty simple but i dont really understand it.

Im following a tutorial on Flutter Clean Architecture and when i'm writing my first test i have an error says "The non-nullable local variable 'mockNumberTriviaRepository' must be assigned before it can be used." I dont know how to write it to be a proper code.

My code is below:

class MockNumberTriviaRepository extends Mock
    implements NumberTriviaRepository {}

void main() {
  GetConcreteNumberTrivia usecase;
  MockNumberTriviaRepository mockNumberTriviaRepository;

  setUp(() {
    MockNumberTriviaRepository mockNumberTriviaRepository = MockNumberTriviaRepository();
    usecase = GetConcreteNumberTrivia(mockNumberTriviaRepository);
  });

  final tNumber = 1;
  final tNumberTrivia = NumberTrivia(number: 1, text: 'test');
  test('schould get trivia for the number from the repository', () async {
    // arrange
    when(**mockNumberTriviaRepository**.getConcreteNumberTrivia(1)).thenAnswer((_) async => Right(tNumberTrivia));
    // act

    // assert
  });
}


Error appears in part between ** ** this signs after the when method in test function

Capriola answered 25/6, 2021 at 13:5 Comment(0)
R
4

The compiler can't really understand that you're initializing the value later. To tell it that you promise to do so before using the variable, add late keyword before the type.

Example:

// compiles successfully and prints 'abc'
void main() {
  late String foo;
  
  (){
    foo = 'abc';
  }();

  print(foo);
}

In your case it will be

late MockNumberTriviaRepository mockNumberTriviaRepository;
Restive answered 25/6, 2021 at 13:11 Comment(0)
B
2

At the top of void main initialize the mockNumberTriviaRepository as

MockNumberTriviaRepository mockNumberTriviaRepository= MockNumberTriviaRepository();

class MockNumberTriviaRepository extends Mock
    implements NumberTriviaRepository {}

void main() {
  GetConcreteNumberTrivia usecase;
  MockNumberTriviaRepository mockNumberTriviaRepository= MockNumberTriviaRepository();

  setUp(() {
   //MockNumberTriviaRepository mockNumberTriviaRepository = MockNumberTriviaRepository();
    usecase = GetConcreteNumberTrivia(mockNumberTriviaRepository);
  });

  final tNumber = 1;
  final tNumberTrivia = NumberTrivia(number: 1, text: 'test');
  test('schould get trivia for the number from the repository', () async {
    // arrange
    when(**mockNumberTriviaRepository**.getConcreteNumberTrivia(1)).thenAnswer((_) async => Right(tNumberTrivia));
    // act

    // assert
  });
}

or use late keyword

late MockNumberTriviaRepository mockNumberTriviaRepository;
Broddy answered 19/8, 2021 at 4:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.