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;


  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 {

void main() {
  setUp(() {});

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

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?


  • 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.