i been trying to unit test a function that takes a function as a parameter the unit test returns null value on the function that im testing so may i ask how to unit test this kind of function in dart.

this is the function that i want to test

final result = await _appStateNotifier.guard(
      () => _authService.requestTempPassword(username: credentials.username),

and this is how i test it but got an error type 'Null' is not a subtype of type 'Future<Result<ErrorObject, String>>'

when(() => mockAuthService.requestTempPassword(username: tCredentials.username))
              .thenAnswer((_) async => successMessage);

when(() => mockStateNotifier.guard(
              () => mockAuthService.requestTempPassword(username: tCredentials.username),
          ).thenAnswer((_) async => const Success(successMessage));

await notifier.onRequestTempPassword(credentials: tCredentials);

and this is the guard clause function

Future<Result<ErrorObject, T>> guard<T>(Future<T> Function() function) async {
try {
  final data = await future();
  return Success(data);
} on FailureException catch (e) {
  return Error(e);
} catch (e, s) {
  return Error(e);


thank you

Solution 1: Lajos Arpad

Your Future<Result<ErrorObject, T>> excludes the possibility of having a Null result. If you want to allow Null, then you need to make it nullable, see https://dart.dev/null-safety/understanding-null-safety

I'm not fluent with Flutter, so the syntax might be off, but as far as I understand, you could change that to

Future<Result<ErrorObject, T>>?

in order to make it nullable. Let me know if I'm totally off with the syntax.


It turns out that the solution finally applied was putting the when method in the setpup function before the test run, as @Ken Verganio described in the comment section.