Flutter单元测试报错:List<dynamic>无法转为List<DocumentReference>
解决Flutter单元测试中List与List类型不匹配错误
问题出在从Firebase读取timerRefs时,Firebase返回的是List<dynamic>类型,但你的TimerSessionModel要求timerRefs是List<DocumentReference<Map<String, dynamic>>>,直接赋值会触发类型转换错误。
修复方案
你需要显式将List<dynamic>转换为目标强类型列表,有两种常用方式:
方式1:使用List.from()创建新列表
这种方式会创建一个全新的强类型列表,适合需要修改列表的场景:
timerRefs: List<DocumentReference<Map<String, dynamic>>>.from(data['timerRefs']),
方式2:使用cast()做类型转换视图
这种方式不会创建新列表,只是给原列表添加类型约束,性能更优,但如果原列表包含非DocumentReference类型的元素,后续操作会报错:
timerRefs: (data['timerRefs'] as List).cast<DocumentReference<Map<String, dynamic>>>(),
修改后的完整代码
factory TimerSessionModel.fromSnapshot( DocumentSnapshot<Map<String, dynamic>> snapshot) { final data = snapshot.data()!; return TimerSessionModel( selfRef: snapshot.reference, activeExecutionRef: data['activeExecutionRef'], autoStartNextTimer: data['autoStartNextTimer'] as bool, ownerRef: data['ownerRef'], timerRefs: List<DocumentReference<Map<String, dynamic>>>.from(data['timerRefs']), title: data['title'] as String, ); }
单元测试注意事项
编写单元测试时,要确保测试数据中的timerRefs是正确的DocumentReference实例(可以用Mock库模拟),比如:
// 使用MockFirebaseFirestore模拟DocumentReference final mockTimerRef = MockDocumentReference<Map<String, dynamic>>(); // 构造测试用的文档数据 final testData = { 'timerRefs': [mockTimerRef], 'autoStartNextTimer': true, 'title': 'Test Session', // 其他必填字段... };
内容的提问来源于stack exchange,提问作者M99Coder
相关产品推荐
相关产品推荐

