Reputation: 361
I am trying to use mockito
in my project to test an API. Here is a small snippet code under organization_test.dart
. I will only provide up until the error line as it is the only concern.
class MockOrganizationRemoteDataSource extends Mock implements OrganizationRemoteDataSource {}
void main(){
late final MockOrganizationRemoteDataSource mockOrganizationDataSource;
late final IOrganizationRepository iOrganizationRepository;
final tOrgName = "someOrgName";
setUp((){
mockOrganizationRemoteDataSource = MockOrganizationRemoteDataSource();
iOrganizationRepository = IOrganizationRepository(mockOrganizationRemoteDataSource);
});
test("Should fetch the organization",() async {
when(mockOrganizationRemoteDataSource.getOrganization(tOrgName)) // Getting ERROR on this line
.thenAnswer(
(_) async => Response(
requestOption: RequestOption(
path: <Some url in here 👌🏼>
data: <Some json response here 👌🏼>
responseType: ResponseType.json)
),
);
final result = await iOrganizationRepository.fetchOrganization(tOrgName);
...
... // some more code here
});
}
Then I get error is type 'Null' is not a subtype of type 'Future<Response<dynamic>>'
I was expecting that if I use mock I can call the getOrganization
method from the mockedDataSource and pretend to answer a response. Yet upon debugging this, I always ending up referencing to the Un-mocked class which is the OrganizationRemoteDataSource
resulting the null value.
BTW I'm using flutter with null-safety enabled and Dio
.
Upvotes: 1
Views: 4219
Reputation: 361
Thanks to jamesdlin's comment I was able to resolve this:
@GenerateMocks
annotation to the void main()
@GenerateMocks([OrganizationRemoveDataSource])
void main(){
...
}
MockOrganizationRemoteDataSource
class and used the build_runner to allow Mockito to generate the annotated GenerateMocks.UPDATE:
Due to the intricacy of using Mockito
in a null-safety dart. I came across a great library that works as alternative named Mocktail
. You can see the library here https://pub.dev/packages/mocktail.
Upvotes: 2