Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: type 'Null' is not a subtype of type 'Future<String?>' in Mockito

Tags:

mockito

dart

The code below used to work before null safety, but now I get "type 'Null' is not a subtype of type 'Future<String?>'" and I have absolutely no idea why and what to do. Please help, this should be really easy (except for me), because you just have to copy the code and run it as test to get the exception:

import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockMethodChannel extends Mock implements MethodChannel {}

void main() {

  group('all', () {

      test('test', () async {
        final mockMethodChannel = MockMethodChannel();
        when(mockMethodChannel
            .invokeMethod<String>("GET com.eight/preference-management/preferences"))
            .thenAnswer((_) async => "test");
      });
  });
}
like image 259
Wolfgang Avatar asked May 03 '21 15:05

Wolfgang


1 Answers

Your signature for MethodChannel.invokeMethod function says it returns a Future<String?> but since the MockMethodChannel doesnot have any implementation for invokeMethod() , it will return null; dart's null safety gets angry because you lied. For a quick fix, the invokeMethod can have a return type of Future<String?>?. When you do so, you are saying null safety shouldn't bother even if the returned value is null.

However this is not a permanent solution I just want you to understand the problem.

you could add build_runner in your dev_dependencies: in pubspec.yaml

dart pub add build_runner --dev

and modify your code to

import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
//modified
import 'package:mockito/annotations.dart';
import 'generated file.dart';

class MockMethodChannel extends Mock implements MethodChannel {}

//modified
@GenerateMocks([MockMethodChannel])
void main() {

  group('all', () {

      test('test', () async {
        final mockMethodChannel = MockMockMethodChannel();
        when(mockMethodChannel
            .invokeMethod<String>("GET com.eight/preference-management/preferences"))
            .thenAnswer((_) async => "test");
      });
  });
}

and run flutter pub run build_runner build --delete-conflicting-outputs for build runner to build the stub files for you

like image 71
Santosh Mainali Avatar answered Sep 18 '22 12:09

Santosh Mainali