Kostya Vyrodov
Kostya Vyrodov

Reputation: 7277

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

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

Upvotes: 8

Views: 7078

Answers (3)

sldon
sldon

Reputation: 31

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

Upvotes: 0

Suragch
Suragch

Reputation: 512526

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.

Upvotes: 6

Jordan Davies
Jordan Davies

Reputation: 10881

You need to override the equality operator in your QuizGameState class.

Upvotes: 0

Related Questions