How to assert objects by its state (all properties values) in a Dart unit test?

Viewed 1116

I have a class (with more properties than the example, of course).

How to write the following simple test? I know that equality in Dart is by object instance. How to compare the full object state? I tested with the same matcher as well, with no luck.

import 'package:test/test.dart';

class UnderTesting {
  var a;
  var b;
  UnderTesting({this.a, this.b});
}

void main() {
  test("compare objects", () {
    final obj1 = UnderTesting(a:1, b:2);
    final obj2 = UnderTesting(a:1, b:2);
    
    // Next will fail because it is checking if it is the same instance
    expect(obj1, equals(obj2));
  } );
}
1 Answers

You need to override the == operator (and should therefore also override hashCode) for UnderTesting. The documentation for equals tells us how to does test for equality:

If [expected] is a [Matcher], then it matches using that. Otherwise it tests for equality using == on the expected value.

So you code should be something like this:

import 'package:test/test.dart';
import 'package:quiver/core.dart';

class UnderTesting {
  int a;
  int b;
  UnderTesting({this.a, this.b});

  @override
  bool operator ==(Object other) =>
      (other is UnderTesting) ? (a == other.a && b == other.b) : false;

  @override
  int get hashCode => hash2(a, b);
}

void main() {
  test("compare objects", () {
    final obj1 = UnderTesting(a: 1, b: 2);
    final obj2 = UnderTesting(a: 1, b: 2);

    expect(obj1, equals(obj2)); // All tests passed!
  });
}

I can recommend the quiver package for making easy hashCode implementations: https://pub.dev/documentation/quiver/latest/quiver.core/quiver.core-library.html

Related