You need to enable JavaScript to run this app. Dart使用ObjectBox时模型转换单元测试失败如何修复
优惠活动
大模型
产品
解决方案
定价
更多

Dart使用ObjectBox时模型转换单元测试失败如何修复

ObjectBox Group转换器单元测试报错修复方案

问题现象

运行Group双向转换器单元测试时触发相等性判断失败,报错截图如下:
单元测试报错截图

问题根因

  • GroupEntity中被@Backlink('group')修饰的students字段是ObjectBox自动维护的只读反向关联,不支持在构造函数中手动传入自定义ToMany实例,手动传入的实例未被ObjectBox代理,会导致后续访问、相等判断异常。
  • Equatable对集合类型默认做引用相等判断,直接将ToMany类型放入props、或者转换时未将关联集合转为普通List做深度转换,会导致值相同但引用不同的对象被判定为不相等,测试断言失败。

修复步骤

  • 修正GroupEntity定义:移除构造函数中students的必填入参,重写props时将ToMany转为普通List做值比较
@Entity()
class GroupEntity extends Equatable {
  GroupEntity({
    this.id = 0,
    required this.groupName,
  });
  int id;
  String groupName;
  @Backlink('group')
  ToMany<StudentEntity> students = ToMany<StudentEntity>();

  @override
  List<Object?> get props => [id, groupName, students.toList()];
}
  • 修正单元测试初始化逻辑:构造GroupEntity时不要手动给Backlink修饰的students字段传值
main() {
  group('Group converter when user add Group', () {
    test('The result should be a database model converted to a local model',
        () {
      final groupConverter = GroupDbConverter();
      final dbModel = GroupEntity(
        id: 1,
        groupName: 'Test group',
      );
      final expected = Group(
        id: 1,
        groupName: 'Test group',
        students: [],
      );
      final actual = groupConverter.inToOut(dbModel);
      expect(actual, expected);
    });
  });
}
  • 检查转换器转换逻辑:确保inToOut方法将ToMany<StudentEntity>深度转换为普通List<Student>,禁止直接将ObjectBox的ToMany对象赋值给本地模型的students字段
// 转换器核心逻辑示例
Group inToOut(GroupEntity entity) {
  return Group(
    id: entity.id,
    groupName: entity.groupName,
    students: entity.students
        .map((studentEntity) => /* 补充你的StudentEntity转Student逻辑 */)
        .toList(),
  );
}
  • (可选优化)修正本地Group模型的props,将List转为不可变集合,避免后续出现集合引用导致的相等判断问题
class Group extends Equatable {
  Group({
    this.id,
    this.groupName,
    this.students,
  });
  int? id;
  String? groupName;
  List<Student>? students;
  @override
  List<Object?> get props => [
        id,
        groupName,
        students != null ? List.unmodifiable(students!) : null,
      ];
}

内容的提问来源于stack exchange,提问作者userName

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 15:33:19