test icon indicating copy to clipboard operation
test copied to clipboard

Missing matcher that expands the matched value

Open feinstein opened this issue 10 months ago • 1 comments

I asked AI to generate some test cases for me and it generated this:

expect(
  () => normalizeAddress(address),
  throwsA(
    predicate((e) =>
        e is InvalidAddressError && _compareErrors(e.errors, expectedErrors)),
  ),
);

bool _compareErrors(Map<AddressField, String> actual, Map<AddressField, String> expected) {
  if (actual.length != expected.length) {
    return false;
  }

  for (final key in expected.keys) {
    if (!actual.containsKey(key) || actual[key] != expected[key]) {
      return false;
    }
  }

  return true;
}

As far as I know, the only way I can check the exception type and inner values without calling the expect twice, is by using a predicate and compare the values manually, as this code shows, but I wanted to refactor it into something like this:

expect(
  () => normalizeAddress(address),
  throwsA(
    allOf([
      isA<InvalidAddressError>,
      map((e) => e.errors, containsAll(expectedErrors))
    ])
  ),
);

Where map would map the current matched value into another one, so we can have access to the current value, for cases like this.

feinstein avatar Apr 23 '25 01:04 feinstein

Actually in this case .having would be enough:

expect(
  () => normalizeAddress(address),
  throwsA(
      isA<InvalidAddressError>.having((e) => errors, "errors", containsAll(expectedErrors)),
  ),
);

benthillerkus avatar Jun 21 '25 14:06 benthillerkus