下面的代码曾经在 null 安全之前工作,但现在我得到“类型 'Null' 不是类型 '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");
});
});
}
您的签名MethodChannel.invokeMethod
函数说它返回一个Future<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");
});
});
}
and run
flutter pub run build_runner build --delete-conflicting-outputs
让构建运行程序为您构建存根文件
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)