颤振测试块错误类型'Null'不是类型的子类型
Posted
技术标签:
【中文标题】颤振测试块错误类型\'Null\'不是类型的子类型【英文标题】:Flutter test bloc error type 'Null' is not a subtype of type颤振测试块错误类型'Null'不是类型的子类型 【发布时间】:2021-10-08 05:53:55 【问题描述】:我正在测试一个从 api 获取餐馆列表的 bloc 方法。
这是我的代码:
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mobile_app_engineer/blocs/merchant_bloc.dart';
import 'package:mobile_app_engineer/repositories/merchant_repository.dart';
import 'package:mockito/mockito.dart';
import 'package:mobile_app_engineer/models/list_merchants_response.dart';
class MockMerchantRepository extends Mock implements MerchantRepository
// Generate a MockClient using the Mockito package.
// Create new instances of this class in each test.
void main()
late MockMerchantRepository mockMerchantRepository;
setUp(()
mockMerchantRepository = MockMerchantRepository();
);
List<Merchant> merchantList = [
Merchant object here
];
blocTest<MerchantBloc, MerchantState>(
'Check if merchant fetch return correct data',
build: ()
when(mockMerchantRepository.fetchMerchants(1)).thenThrow(NetworkError()); <=== in this line main 101
return MerchantBloc(mockMerchantRepository);
,
act: (bloc) => bloc.add(GetMerchantsList(1)),
expect: () => [MerchantInitial(), GetMerchantsListState(merchantList)],
);
我收到此错误:
type 'Null' is not a subtype of type 'Future<List<Merchant>>'
package:mobile_app_engineer/repositories/merchant_repository.dart 14:26
MockMerchantRepository.fetchMerchants
test/api_test/fetch_restaurant_test.dart 101:35 main.<fn>
package:bloc_test/src/bloc_test.dart 176:25 testBloc.<fn>
我做错了什么吗?谢谢
【问题讨论】:
有MerchantState
和fetchMerchants()
的详细代码
【参考方案1】:
找到解决方案:这是因为 null 安全性,所以现在我不得不添加 GenerateMocks 来为 api 调用生成一个模拟存储库。
import 'fetch_merchant_test.mocks.dart';
@GenerateMocks([MockMerchantRepository])
void main()
final mockMerchantRepository = MockMockMerchantRepository();
【讨论】:
以上是关于颤振测试块错误类型'Null'不是类型的子类型的主要内容,如果未能解决你的问题,请参考以下文章
颤振错误:类型“int”不是类型转换中“String”类型的子类型
颤振:类型“Future<dynamic>”不是“Widget”类型的子类型?错误