Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  });
like image 387
Kostya Vyrodov Avatar asked Jan 02 '19 13:01

Kostya Vyrodov


People also ask

How do you compare two objects in the same class?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

How do you compare values in objects?

Referential equality JavaScript provides 3 ways to compare values: The strict equality operator === The loose equality operator == Object.is() function.

How do you compare two items?

There are two basic formats to Comparing or Contrasting two items. If one were to compare apples and oranges, for example, we would consider the fruits the items, and qualities such as flavor, color, texture, "juicability" and the like as the aspects.

How can you tell if two objects are the same?

To determine if two objects are not identical Set up a Boolean expression to test the two objects. In your testing expression, use the IsNot operator with the two objects as operands. IsNot returns True if the objects do not point to the same class instance.


Video Answer


1 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.

like image 96
Suragch Avatar answered Sep 25 '22 17:09

Suragch