Skip to content

Commit

Permalink
fix(built_value_test): respect non comparable fields
Browse files Browse the repository at this point in the history
Signed-off-by: Nikolas Rimikis <leptopoda@users.noreply.github.com>
  • Loading branch information
Leptopoda committed Sep 12, 2024
1 parent 153e6ba commit 3f68088
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
12 changes: 10 additions & 2 deletions built_value_test/lib/matcher.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import 'package:matcher/matcher.dart';
/// Returns a matcher that matches if the value is structurally equal to
/// [expected].
///
/// When [onlyCheckComparable] fields that are not comparable are ignored for
/// the equality check.
///
/// Improves on a simple equality test by offering a detailed mismatch message.
Matcher equalsBuilt(Built expected) => _BuiltValueMatcher(expected);
Matcher equalsBuilt(Built expected, {bool onlyCheckComparable = false}) =>
_BuiltValueMatcher(expected, onlyCheckComparable);

/// Matcher for [Built] instances.
///
Expand All @@ -19,8 +23,10 @@ Matcher equalsBuilt(Built expected) => _BuiltValueMatcher(expected);
class _BuiltValueMatcher implements Matcher {
final Built _expected;
final Matcher _delegate;
final bool _onlyCheckComparable;

_BuiltValueMatcher(this._expected) : _delegate = equals(_toMap(_expected));
_BuiltValueMatcher(this._expected, this._onlyCheckComparable)
: _delegate = equals(_toMap(_expected));

@override
Description describe(Description description) =>
Expand All @@ -41,6 +47,8 @@ class _BuiltValueMatcher implements Matcher {
bool matches(dynamic item, Map matchState) {
if (_expected.runtimeType != item.runtimeType) return false;

if (_onlyCheckComparable && _expected == item) return true;

return _delegate.matches(_toMap(item), matchState);
}
}
Expand Down
18 changes: 16 additions & 2 deletions built_value_test/test/matcher_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,14 @@ void main() {
..name = 'foo'
..onChanged = () => 'Change happened!');

expect(value, otherValue);
expect(value, isNot(equalsBuilt(otherValue)));
expect(
value,
equalsBuilt(
otherValue,
onlyCheckComparable: true,
),
);
});

test('compared value matcher with different onChanged outcomes', () {
Expand All @@ -114,7 +121,14 @@ void main() {
..name = 'foo'
..onChanged = () => 'Change did not happen!');

expect(value, otherValue);
expect(value, isNot(equalsBuilt(otherValue)));
expect(
value,
equalsBuilt(
otherValue,
onlyCheckComparable: true,
),
);
});

test('compared value matcher with different names', () {
Expand Down

0 comments on commit 3f68088

Please sign in to comment.