I'm trying to learn Flutter and 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?
Thanks.
CodePudding user response:
@GenerateMocks([RandomWordsRepository])
will create a MockRandomWordsRepository
class for you. You should not be defining it yourself. You additionally will need to run dart run build_runner build
to generate the mocks and 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.