flutterunit-testingdartmockitotdd

Mockito mocked function returned Null


I got stuck on making the test using Mockito. I'm trying to implement Clean Architect to the Flutter tutorial https://docs.flutter.dev/get-started/codelab. I've made a use case called GetRandomWords and an interface-adapter called RandomWordsRepository like so:

abstract class RandomWordsRepository {
  String get();
}

abstract class GetRandomWords {
  String randomWords();
}

class GetRandomWordsImpl implements GetRandomWords {
  final RandomWordsRepository repository;

  GetRandomWordsImpl(this.repository);

  @override
  String randomWords() {
    return repository.get();
  }

}

I've made a test case like this:

import 'package:mockito/mockito.dart';
import 'package:tutorial/domain/interfaces/random_words_repository.dart';
import 'package:tutorial/domain/use_cases/get_random_words.dart';

class MockRandomWordsRepository extends Mock implements RandomWordsRepository {
}

@GenerateMocks([RandomWordsRepository])
void main() {
  setUp(() {});

  test("Should get random words from repository", () async {
    final expectedRandomWords = "test_random_words";
    final mockRepository = MockRandomWordsRepository();
    final useCase = GetRandomWordsImpl(mockRepository);
    when(mockRepository.get()).thenReturn(expectedRandomWords);
    
    expect(useCase.randomWords(), expectedRandomWords);
    verify(mockRepository.get());
  });
}

But it returned this error: type 'Null' is not a subtype of type 'String' on the line when(mockRepository.get()).thenReturn(expectedRandomWords);. Can anybody tell me what went wrong here?


Solution

  • You are following some old Mockito example that predates Dart null-safety.

    With null-safety, you should not be defining the MockRandomWordsRepository class (or other mock classes) yourself. You instead will need to generate the mock classes with @GenerateMocks([RandomWordsRepository]) or @GenerateNiceMocks([RandomWordsRepository]) and then running dart run build_runner build. You then will need to add an appropriate import line to use the generated file.

    Make sure that you follow the instructions from the Mockito README precisely.