Code Spirit
Code Spirit

Reputation: 5061

How to change expect text in dart test

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.

Upvotes: 1

Views: 265

Answers (1)

jamesdlin
jamesdlin

Reputation: 90025

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

Upvotes: 1

Related Questions