如何比较相同类型的两个对象的值?

Kos*_*dov 7 dart flutter flutter-test

我需要为 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);
  });
Run Code Online (Sandbox Code Playgroud)

Sur*_*gch 6

如何覆盖==相等性测试

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

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;
}
Run Code Online (Sandbox Code Playgroud)

上面的例子来自这篇文章,建议您使用Equitable包来简化流程。这篇文章也值得一读。


Jor*_*ies 0

您需要重写类中的相等运算QuizGameState符。