使用Mockito测试含auto_mappr的convertList时类型错误问题排查
问题解答
1. 异常抛出原因
auto_mappr的convertList方法要求传入参数必须是List类型,不接受null。你的仓库函数在调用convertList时,传入的数据源(比如API返回的DTO列表)是null,直接传递给convertList就会触发type 'Null' is not a subtype of type 'List<dynamic>'类型转换异常。
常见触发场景:
- 后端API返回
null而非空数组 - 测试时mock的数据源返回
null - 仓库函数未对数据源做判空处理,直接传递给
convertList
2. 如何测试call函数
针对仓库的call函数,需要分正常场景和边界异常场景测试,核心是mock好依赖的数据源,确保传入convertList的参数符合预期:
步骤1:Mock依赖数据源
不管仓库依赖API服务还是本地存储,都要创建mock实例来控制返回值,避免依赖真实外部服务。可以手动mock或用Mockito框架实现。
步骤2:编写测试用例
场景1:数据源返回有效列表
验证call函数能正确调用convertList并返回转换后的实体列表:
test('call returns converted entities when data exists', () async { // 准备测试DTO数据 final testDtos = [UserDto('张三'), UserDto('李四')]; // mock数据源返回有效列表 mockApi.whenGetUsers(() async => testDtos); // 执行仓库调用 final result = await repository(); // 验证转换结果 expect(result.length, 2); expect(result[0].name, '张三'); });
场景2:数据源返回null
测试仓库对null的处理逻辑(需先在仓库中添加判空逻辑,比如将null转为空列表或抛出自定义异常):
test('call returns empty list when data is null', () async { // mock数据源返回null mockApi.whenGetUsers(() async => null); // 执行仓库调用 final result = await repository(); // 验证返回空列表(前提是仓库做了dtos ?? []的处理) expect(result, isEmpty); });
仓库函数修复建议
为避免异常,必须在调用convertList前增加判空处理:
Future<List<UserEntity>> call() async { final dtos = await api.getUsers(); // 将null转为空列表,避免传递给convertList触发异常 return mappr.convertList<UserDto, UserEntity>(dtos ?? []); }
内容的提问来源于stack exchange,提问作者Sebastian Schucht
相关产品推荐
相关产品推荐

