Mockito – stub a method after the null-safety migration

Issue

Before the null safety I could simply mock up the sendRequest(…) method like that:

 void stubBaseRepositorySendRequestResponse(String response) {
    when(baseRepository.sendRequest(onGetData: anyNamed('onGetData')))
        .thenAnswer((_) {
      return Future<String>.value(response);
    });
  }

where the signature of this method is:

Future<T> sendRequest<T>({required Future<T> Function() onGetData})

How can this be done with the new null-safe version of mockito?
Can I still maintain the generic character of this stub and allow for any arguments to be passed in?

Solution

This can be easily done with mocktail.
A lot easier, without the code gen required by mockito.

Important to import mocktail first:

import 'package:mocktail/mocktail.dart';

then create a mock of the class that we want to mock:

class MockBaseRepository extends Mock implements BaseRepository {}

void stubBaseRepositorySendRequestResponse(String response) {
when(() => baseRepository.sendRequest(
        onGetData: any(named: 'onGetData', that: isNotNull))).thenAnswer((_) {
      return Future<String>.value(response);
    });
  }

Answered By – Pablito

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *