Rares Cruceat
Rares Cruceat

Reputation: 103

How to mock a future method and not get type 'Null' is not a subtype of type 'Future<>' in flutter

I want to mock this class and this specific method

class FeedApiService extends ApiService {
  Future<FeedResponse> fetchFeed(Map<String, String> params) async {
    ...
  }
  ...
}

My unit test is like this

class FeedApiServiceMock extends Mock implements FeedApiService {}
void main() {
  test('..', () {
    FeedApiServiceMock feedApiServiceMock = FeedApiServiceMock();
    when(feedApiServiceMock.fetchFeed({})).thenAnswer(
        (_) => Future.value(FeedResponse(items: 1)),
      );
    expect(await feedApiServiceMock.fetchFeed({}).items, 1);
  });
}

I just want to see that fetch feed is mocked correctly, but I'm getting this error:

type 'Null' is not a subtype of type 'Future<FeedResponse>'

Upvotes: 6

Views: 2172

Answers (1)

croxx5f
croxx5f

Reputation: 5733

See if adding async in both the test and thenAnswer method solves the problem.

void main() {
  test('..', () async{
    FeedApiServiceMock feedApiServiceMock = FeedApiServiceMock();
    when(feedApiServiceMock.fetchFeed({})).thenAnswer(
        (_) async=> Future.value(FeedResponse(items: 1)),
      );
    expect(await feedApiServiceMock.fetchFeed({}).items, 1);
  });
}

Upvotes: 1

Related Questions