【问题标题】:How to compare values of two objects of the same type?如何比较相同类型的两个对象的值?
【发布时间】:2019-05-29 03:17:18
【问题描述】:

我需要为 Flutter 项目编写单元测试,如果有一个函数可以遍历相同类型的两个不同对象的所有属性以确保所有值相同,我会很高兴。

代码示例:

void main() {
  test('startLoadingQuizReducer sets isLoading true', () {
    var initState = QuizGameState(null, null, null, false);
    var expectedState = QuizGameState(null, null, null, true);

    var action = StartLoadingQuiz();
    var actualState = quizGameReducer(initState, action);
    // my test fails here 
    expect(actualState, expectedState);
  });

【问题讨论】:

    标签: dart flutter flutter-test


    【解决方案1】:

    如何覆盖== 进行相等性测试

    下面是一个覆盖== 运算符的示例,以便您可以比较两个相同类型的对象。

    class Person {
      final String name;
      final int age;
      
      const Person({this.name, this.age});
      
      @override
      bool operator ==(Object other) =>
        identical(this, other) ||
        other is Person &&
        runtimeType == other.runtimeType &&
        name == other.name &&
        age == other.age;
    
      @override
      int get hashCode => name.hashCode ^ age.hashCode;
    }
    

    上面的例子来自this article,建议你使用Equitable包来简化流程。 This article也值得一读。

    【讨论】:

      【解决方案2】:

      您需要覆盖 QuizGameState 类中的 equality operator

      【讨论】:

      • 如果你这样做,不要忘记覆盖 hashCode。否则,Set 和其他人会崩溃。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多