Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider CoreChecks.isEquivalentTo #2443

Open
matanlurey opened this issue Dec 30, 2024 · 0 comments
Open

Consider CoreChecks.isEquivalentTo #2443

matanlurey opened this issue Dec 30, 2024 · 0 comments
Labels
package:checks Issues related to pkg:checks type-enhancement A request for a change that isn't a bug

Comments

@matanlurey
Copy link
Contributor

In Dart, an object that implements equality in respect to another object is expected to:

  • a == b
  • a.hashCode == b.hashCode

(It's possible for hashCode's to be equal, but not exact equality, for inequal objects)

To test this feature in my code, I often write a helper like:

extension CoreChecksX<T extends Object?> on Subject<T> {
  /// Expects that this value is equivalent to [other].
  ///
  /// Two objects are considered equivalent if they are equal and have the same
  /// hash code.
  void isEquivalentTo(T other) {
    context.expect(() => prefixFirst('equals ', literal(other)), (actual) {
      if (actual != other) {
        return Rejection(which: ['are not equal']);
      }
      if (actual.hashCode != other.hashCode) {
        return Rejection(which: ['have different hash codes']);
      }
      return null;
    });
  }
}

This often catches subtle bugs where a new field is added, but only == is updated and not hashCode.

Would you consider this in the library itself? I also often introduce hasToString:

/// Returns a subject that expects the [Object.toString] representation of
/// this value.
Subject<String> get hasToString {
  return context.nest<String>(
    () => ['has a string representation'],
    (actual) => Extracted.value(actual.toString()),
    atSameLevel: true,
  );
}

... but happy to consider that separately if you're all interested.

@matanlurey matanlurey added type-enhancement A request for a change that isn't a bug package:checks Issues related to pkg:checks labels Dec 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
package:checks Issues related to pkg:checks type-enhancement A request for a change that isn't a bug
Projects
None yet
Development

No branches or pull requests

1 participant