How to compare values of two objects of the same type?

Viewed 5173

I need to write unit tests for a Flutter project and I would be happy if there is a function that can go through all properties of two different objects of a same type to make sure that all values are same.

Code sample:

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);
  });
3 Answers

How to override == for equality testing

Here is an example of overriding the == operator so that you can compare two objects of the same type.

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;
}

The example above comes from this article, which is recommending that you use the Equitable package to simplify the process. This article is also worth reading.

Add to the answer provided here, if the object has a list in it you will have to compare the list separately like explained Compare lists for equality

Related