You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter单元测试中Right<Failure, List>相等性校验失败求助

解决Flutter相等性单元测试失败问题

测试代码:

expect(result, equals(Right<Failure, List>(userTestEntityList)));

测试失败异常:

TestFailure (Expected: Right<Failure, List>:<Right([UserEntity(1, lolo, Laurent, Marin), UserEntity(2, roro, Robert, Redford)])> Actual: Right<Failure, List>:<Right([UserEntity(1, lolo, Laurent, Marin), UserEntity(2, roro, Robert, Redford)])> )

我已经尝试过两种方式定义UserEntity类,但问题仍未解决:

1. 使用Equatable实现

import 'package:equatable/equatable.dart';

class UserEntity extends Equatable {
  const UserEntity({
    this.id,
    this.pseudo,
    this.firstName,
    this.lastName,
  });

  /// A description for id
  final int? id;

  /// A description for pseudo
  final String? pseudo;

  /// A description for firstName
  final String? firstName;

  /// A description for lastName
  final String? lastName;

  @override
  List<Object?> get props => [
        id,
        pseudo,
        firstName,
        lastName,
      ];
    
}

2. 重写operator==和hashCode

class UserEntity {
  const UserEntity({
    this.id,
    this.pseudo,
    this.firstName,
    this.lastName,
  });

  /// A description for id
  final int? id;

  /// A description for pseudo
  final String? pseudo;

  /// A description for firstName
  final String? firstName;

  /// A description for lastName
  final String? lastName;


  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is UserEntity &&
          runtimeType == other.runtimeType &&
          id == other.id &&
          pseudo == other.pseudo &&
          firstName == other.firstName &&
          lastName == other.lastName;

  @override
  int get hashCode =>
      id.hashCode ^ pseudo.hashCode ^ firstName.hashCode ^ lastName.hashCode;

}

问题原因与解决方案

问题出在List的相等性检查上:Dart中普通List的==默认是引用相等,即使两个List的元素完全一致,只要是不同的实例,就会判定为不相等。而当前测试直接比较整个Right对象,其内部的List会用默认的引用相等规则判定,导致测试失败。

你可以通过以下两种方式解决:

方式一:拆分检查,单独验证List元素

先确认result是Right类型,再用orderedEquals(要求元素顺序一致)或unorderedEquals(不要求顺序)验证内部List的元素:

// 先验证类型
expect(result, isA<Right<Failure, List<UserEntity>>>());
// 再验证List元素相等
expect((result as Right<Failure, List<UserEntity>>).value, orderedEquals(userTestEntityList));

方式二:使用自定义的可比较List(比如EquatableList)

如果你希望List本身能通过元素相等来判定相等,可以使用equatable包提供的EquatableList,这样在比较Right对象时,内部的List会按元素相等规则判定:

// 使用EquatableList创建测试列表
final userTestEntityList = EquatableList.of([
  UserEntity(id: 1, pseudo: 'lolo', firstName: 'Laurent', lastName: 'Marin'),
  UserEntity(id: 2, pseudo: 'roro', firstName: 'Robert', lastName: 'Redford'),
]);

// 测试代码保持不变,泛型指定为EquatableList<UserEntity>
expect(result, equals(Right<Failure, EquatableList<UserEntity>>(userTestEntityList)));

另外,建议明确指定泛型类型为List<UserEntity>而非List,这样类型检查更严格,也能避免潜在的类型相关问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:12:03