expectEqualStrings function

void expectEqualStrings(
  1. String actual,
  2. String expected, {
  3. String? reason,
})

Finds the first difference between two strings and highlights it in red.

Implementation

void expectEqualStrings(String actual, String expected, {String? reason}) {
  final expectedLines = expected.split('\n');
  final actualLines = actual.split('\n');

  for (var i = 0; i < expectedLines.length && i < actualLines.length; i++) {
    if (expectedLines[i] != actualLines[i]) {
      final highlightedExpected =
          _highlightDifference(expectedLines[i], actualLines[i]);
      final highlightedActual =
          _highlightDifference(actualLines[i], expectedLines[i]);

      throw TestFailure('''
${reason ?? 'Strings do not match'}:
Difference at line ${i + 1}:

Expected: $highlightedExpected

Actual  : $highlightedActual
''');
    }
  }

  if (expectedLines.length != actualLines.length) {
    throw TestFailure('''
${reason ?? 'Strings do not match'}:
Difference in number of lines:
Expected ${expectedLines.length} lines, but got ${actualLines.length}
''');
  }
}