下面的代码曾经在空安全之前工作,但现在我得到“类型 'Null' 不是类型 'Futureimport '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 安全会因为你撒谎而生气。如需快速修复,请使用 invokeMethod
可以有 Future<String?>?
的返回类型.当您这样做时,您是在说即使返回值为 null 也不应该打扰 null 安全。
然而,这不是一个永久的解决方案,我只是想让你理解这个问题。
您可以在 dev_dependencies: in pubspec.yaml 中添加 build_runnerdart 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
用于构建运行器为您构建 stub 文件
关于Dart:类型 'Null' 不是 Mockito 中类型 'Future<String?>' 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67371802/