Dart:'Null' 类型不是 Mockito 中类型 'Future<String?>' 的子类型

Wol*_*ang 13 mockito dart

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

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");
      });
  });
}
Run Code Online (Sandbox Code Playgroud)

San*_*ali 20

您的函数签名MethodChannel.invokeMethod表示它返回 aFuture<String?>但由于MockMethodChannel没有任何实现invokeMethod(),因此它将返回null; dart 的 null safety 会因为你撒谎而生气。为了快速修复,invokeMethod可以将返回类型设置为Future<String?>?. 当您这样做时,您是在说即使返回值为 null,空安全也不应该打扰。

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

您可以在 dev_dependency: pubspec.yaml 中添加 build_runner

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");
      });
  });
}
Run Code Online (Sandbox Code Playgroud)

并运行 flutter pub run build_runner build --delete-conflicting-outputs构建运行程序来为您构建存根文件


Agu*_*ana 9

如果您使用具有 null 安全性的 Flutter,那么创建模拟类的方式会有所不同,您@GenerateMocks现在需要使用注释。

请阅读有关空安全的文档