1

Is there a possibility to change the text that is printed if a dart expect fails?

It works fine with primitives but working with lists of objects makes it really hard to find the difference.

UPDATE

Testing library uses toString() method to display the value diffs in the test result. I am using freezed so by default this will just dump all the object properties.
A solution is to implement a custom toString in your class to alter how objects are displayed in test result.

Code Spirit
  • 3,992
  • 4
  • 23
  • 34

1 Answers1

1

Use the reason parameter to expect:

import 'package:test/test.dart';

void main() {
  test('Example', () {
    var data = ['duck', 'duck', 'goose'];
    for (var i = 0; i < data.length; i += 1) {
      expect(data[i], 'duck', reason: 'Failed on iteration $i');
    }
  });
}

prints:

00:00 +0 -1: Example [E]

  Expected: 'duck'
    Actual: 'goose'
     Which: is different.
            Expected: duck
              Actual: goose
                      ^
             Differ at offset 0
  Failed on iteration 2
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • Thanks for the reply but the problem still persists because in your example you have used just strings. The problem becomes more clear to when testing a stream that emits multiple events with `emits` or `emitsInOrder` where each event is a list of 10 items each being an object with around 10 properties including nested objects. – Code Spirit Jun 10 '22 at 19:37
  • @CodeSpirit The `String` part is not relevant; what's relevant is that this example just does a simple iteration over a list. It would help if you gave a more specific example of the case you're trying to handle and what kind of message you want. – jamesdlin Jun 10 '22 at 19:40