【问题标题】:Dart: type 'Null' is not a subtype of type 'Future<String?>' in MockitoDart:类型“Null”不是 Mockito 中“Future<String?>”类型的子类型
【发布时间】:2021-05-03 15:41:33
【问题描述】:

下面的代码曾经在 null 安全之前工作,但现在我得到“type 'Null' is not a subtype of type 'Future'”,我完全不知道为什么以及该怎么做。请帮忙,这应该很容易(除了我),因为您只需复制代码并将其作为测试运行即可获得异常:

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");
      });
  });
}

【问题讨论】:

  • 我们在 mockito 中添加了 null 安全性,更改了类的模拟,看看这个,我一直在努力解决它:github.com/dart-lang/mockito/issues/403,你也可以看看文档: github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md,切换有点麻烦,如果您需要进一步的帮助,请告诉我。
  • 效果很好,非常感谢!只需添加以下内容,一切都很好:` import 'preference_datasource_test.mocks.dart'; @GenerateMocks([], customMocks: [MockSpec(as: #MockMethodChannel)]) `
  • 太棒了!!我很高兴你设法解决了这个问题!
  • 有没有机会支持我的评论?

标签: dart mockito


【解决方案1】:

您对MethodChannel.invokeMethod 函数的签名说它返回一个Future&lt;String?&gt;,但由于MockMethodChannel 没有任何invokeMethod() 的实现,它将返回null; dart 的 null 安全性因为你撒谎而生气。为了快速修复,invokeMethod 的返回类型可以是 Future&lt;String?&gt;?。当你这样做时,你是在说即使返回值为 null 也不应该打扰 null 安全性。

但这不是一个永久的解决方案,我只是想让你理解这个问题。

你可以在你的 dev_dependencies 中添加 build_runner:在 pubspec.yaml 中

dart pub add build_runner --dev

并将您的代码修改为

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");
      });
  });
}

然后运行 flutter pub run build_runner build --delete-conflicting-outputs 用于构建运行器为您构建存根文件

【讨论】:

    【解决方案2】:

    如果你使用的是null安全的Flutter,那么创建mock类的方式就不同了,你现在需要使用@GenerateMocks注解。

    请阅读documentation on null safety

    【讨论】:

      【解决方案3】:

      如果你想要一个简单的方法,就这样做

         class WorkerAPI {
               late ApiHelper _helper;
              
                WorkerAPI() {
                  _helper = GetIt.I<ApiHelper>();
                }
              
                Future<Result<List<WorkerModel>>> getWorkers() async {
                  return await _helper.get(
                      url: urls.workers,
                      onSuccess: (response) {
                        Iterable listJson = json.decode(response.body);
                        List<WorkerModel> list =
                            listJson.map((e) => WorkerModel.fromJson(e)).toList();
                        return list;
                      });
                }
          
           // override your method in mock with Non-nullable return type
          
            class WorkerApiMock extends Mock implements WorkerAPI {
                @override
                Future<Result<List<WorkerModel>>> getWorkers() {
                   return super.noSuchMethod(Invocation.method(#getWorkers,null),
                   returnValue:Future.value(Result.success(List.filled(0,WorkerModel()))));
              }
          
          }
      

      如果你想检查这个 => https://github.com/dart-lang/mockito/blob/master/test/manual_mocks_test.dart

      【讨论】:

        猜你喜欢
        • 2020-10-13
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        • 1970-01-01
        • 2020-12-09
        • 2020-08-11
        • 1970-01-01
        相关资源
        最近更新 更多