Flutter Mockito. Failing to mock

2,029

Thanks to jamesdlin's comment I was able to resolve this:

  • Add @GenerateMocks annotation to the void main()

@GenerateMocks([OrganizationRemoveDataSource])
void main(){
...
}

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

Share:
2,029
GhoSt
Author by

GhoSt

Updated on December 29, 2022

Comments

  • GhoSt
    GhoSt over 1 year

    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.

    • jamesdlin
      jamesdlin almost 3 years
      Did you follow the null-safety instructions and call @GenerateMocks?
    • GhoSt
      GhoSt almost 3 years
      Apparently, I have not and doesn't know that. Will check now. Thanks! I'll ask again if I still get the same error.
    • GhoSt
      GhoSt almost 3 years
      Thanks @jamesdlin! It worked using the @GenerateMocks.