Dart API Referenceunittest

unittest library

A library for writing dart unit tests.

To import this library, specify the relative path to pkg/unittest/unittest.dart.

Concepts

  • Tests: Tests are specified via the top-level function test, they can be organized together using group.

  • Checks: Test expectations can be specified via expect
  • Matchers: expect assertions are written declaratively using Matchers
  • Configuration: The framework can be adapted by calling configure with a Configuration. Common configurations can be found in this package under: 'dom\config.dart' (deprecated), 'html\config.dart' (for running tests compiled to Javascript in a browser), and 'vm\_config.dart' (for running native Dart tests on the VM).

Examples

A trivial test:

#import('path-to-dart/pkg/unittest/unitest.dart');
main() {
  test('this is a test', () {
    int x = 2 + 3;
    expect(x, equals(5));
  });
}

Multiple tests:

#import('path-to-dart/pkg/unittest/unitest.dart');
main() {
  test('this is a test', () {
    int x = 2 + 3;
    expect(x, equals(5));
  });
  test('this is another test', () {
    int x = 2 + 3;
    expect(x, equals(5));
  });
}

Multiple tests, grouped by category:

#import('path-to-dart/pkg/unittest/unitest.dart');
main() {
  group('group A', () {
    test('test A.1', () {
      int x = 2 + 3;
      expect(x, equals(5));
    });
    test('test A.2', () {
      int x = 2 + 3;
      expect(x, equals(5));
    });
  });
  group('group B', () {
    test('this B.1', () {
      int x = 2 + 3;
      expect(x, equals(5));
    });
  });
}

Asynchronous tests: if callbacks expect between 0 and 2 positional arguments, depending on the suffix of expectAsyncX(). expectAsyncX() will wrap a function into a new callback and will not consider the test complete until that callback is run. A count argument can be provided to specify the number of times the callback should be called (the default is 1).

#import('path-to-dart/pkg/unittest/unitest.dart');
#import('dart:html');
main() {
  test('calllback is executed once', () {
    // wrap the callback of an asynchronous call with [expectAsync0] if
    // the callback takes 0 arguments...
    window.setTimeout(expectAsync0(() {
      int x = 2 + 3;
      expect(x, equals(5));
    }), 0);
  });
  test('calllback is executed twice', () {
    var callback = expectAsync0(() {
      int x = 2 + 3;
      expect(x, equals(5));
    }, count: 2); // <-- we can indicate multiplicity to [expectAsync0]
    window.setTimeout(callback, 0);
    window.setTimeout(callback, 0);
  });
}

expectAsyncX() will wrap the callback code in a try/catch handler to handle exceptions (treated as test failures). There may be times when the number of times a callback should be called is non-deterministic. In this case a dummy callback can be created with expectAsync0((){}) and this can be called from the real callback when it is finally complete. In this case the body of the callback should be protected within a call to guardAsync(); this will ensure that exceptions are properly handled.

Note: due to some language limitations we have to use different functions depending on the number of positional arguments of the callback. In the future, we plan to expose a single expectAsync function that can be used regardless of the number of positional arguments. This requires new langauge features or fixes to the current spec (e.g. see Issue 2706).

Meanwhile, we plan to add this alternative API for callbacks of more than 2 arguments or that take named parameters. (this is not implemented yet, but will be coming here soon).

#import('path-to-dart/pkg/unittest/unitest.dart');
#import('dart:html');
main() {
  test('calllback is executed', () {
    // indicate ahead of time that an async callback is expected.
    var async = startAsync();
    window.setTimeout(() {
      // Guard the body of the callback, so errors are propagated
      // correctly
      guardAsync(() {
        int x = 2 + 3;
        expect(x, equals(5));
      });
      // indicate that the asynchronous callback was invoked.
      async.complete();
    }), 0);
  });

Properties

const Matcher anything #

A matcher that matches any value.

const Matcher anything = const _IsAnything();

Matcher completes #

Matches a Future that completes successfully with a value. Note that this creates an asynchronous expectation. The call to expect() that includes this will return immediately and execution will continue. Later, when the future completes, the actual expectation will run.

To test that a Future completes with an exception, you can use throws and throwsA.

Matcher completes = const _Completes(null);

final Configuration config #

Configuration get config => _config;

const ERROR #

const ERROR = 'error';

const FAIL #

const FAIL  = 'fail';

String groupSep #

Separator used between group names and test names.

String groupSep = ' ';

const Matcher happenedAtLeastOnce #

happenedAtLeastOnce matches one or more calls.

const Matcher happenedAtLeastOnce = const _TimesMatcher(1);

const Matcher happenedAtMostOnce #

happenedAtMostOnce matches zero or one call.

const Matcher happenedAtMostOnce = const _TimesMatcher(0, 1);

const Matcher happenedOnce #

happenedOnce matches exactly one call.

const Matcher happenedOnce = const _TimesMatcher(1, 1);

const isArgumentError #

A matcher for ArgumentErrors.

const isArgumentError = const _ArgumentError();

const Matcher isEmpty #

Returns a matcher that matches empty strings, maps or collections.

const Matcher isEmpty = const _Empty();

const isException #

A matcher for Exceptions.

const isException = const _Exception();

const Matcher isFalse #

A matcher that matches anything except the Boolean value true.

const Matcher isFalse = const _IsFalse();

const isFormatException #

A matcher for FormatExceptions.

const isFormatException = const _FormatException();

const isIllegalJSRegExpException #

A matcher for IllegalJSRegExpExceptions.

const isIllegalJSRegExpException = const _IllegalJSRegExpException();

const isIndexOutOfRangeException #

A matcher for IndexOutOfRangeExceptions.

const isIndexOutOfRangeException = const _IndexOutOfRangeException();

const Matcher isNegative #

A matcher which matches if the match argument is negative.

const Matcher isNegative =
  const _OrderingComparison(0, false, true, false, 'a negative value', false);

const Matcher isNonNegative #

A matcher which matches if the match argument is zero or positive.

const Matcher isNonNegative =
  const _OrderingComparison(0, true, false, true,
      'a non-negative value', false);

const Matcher isNonPositive #

A matcher which matches if the match argument is zero or negative.

const Matcher isNonPositive =
  const _OrderingComparison(0, true, true, false,
      'a non-positive value', false);

const Matcher isNonZero #

A matcher which matches if the match argument is non-zero.

const Matcher isNonZero =
  const _OrderingComparison(0, false, true, true, 'a value not equal to');

const isNoSuchMethodError #

A matcher for NoSuchMethodErrors.

const isNoSuchMethodError = const _NoSuchMethodError();

const isNotImplementedException #

A matcher for NotImplementedExceptions.

const isNotImplementedException = const _NotImplementedException();

const Matcher isNotNull #

A matcher that matches any non-null value.

const Matcher isNotNull = const _IsNotNull();

const Matcher isNull #

A matcher that matches any null value.

const Matcher isNull = const _IsNull();

const isNullPointerException #

A matcher for NullPointerExceptions.

const isNullPointerException = const _NullPointerException();

const Matcher isPositive #

A matcher which matches if the match argument is positive.

const Matcher isPositive =
  const _OrderingComparison(0, false, false, true, 'a positive value', false);

const Matcher isTrue #

A matcher that matches the Boolean value true.

const Matcher isTrue = const _IsTrue();

const isUnsupportedOperationException #

A matcher for UnsupportedOperationExceptions.

const isUnsupportedOperationException = const _UnsupportedOperationException();

const Matcher isZero #

A matcher which matches if the match argument is zero.

const Matcher isZero =
  const _OrderingComparison(0, true, false, false, 'a value equal to');

const Matcher neverHappened #

neverHappened matches zero calls.

const Matcher neverHappened = const _TimesMatcher(0, 0);

const PASS #

Test case result strings.

const PASS  = 'pass';

const Matcher returnsNormally #

A matcher that matches a function call against no exception. The function will be called once. Any exceptions will be silently swallowed. The value passed to expect() should be a reference to the function. Note that the function cannot take arguments; to handle this a wrapper will have to be created.

const Matcher returnsNormally = const _ReturnsNormally();

LogEntryList sharedLog #

The shared log used for named mocks.

LogEntryList sharedLog = null;

final testCases #

Get the list of tests.

get testCases => _tests;

Map testState #

A map that can be used to communicate state between a test driver or main() function and the tests, particularly when these two are otherwise independent. For example, a test driver that starts an HTTP server and then runs tests that access that server could use this as a way of communicating the server port to the tests.

Map testState = {};

const Matcher throws #

This can be used to match two kinds of objects:

  • A Function that throws an exception when called. The function cannot take any arguments. If you want to test that a function expecting arguments throws, wrap it in another zero-argument function that calls the one you want to test.

  • A Future that completes with an exception. Note that this creates an asynchronous expectation. The call to expect() that includes this will return immediately and execution will continue. Later, when the future completes, the actual expectation will run.

const Matcher throws = const Throws();

const Matcher throwsArgumentError #

A matcher for functions that throw ArgumentError

const Matcher throwsArgumentError =
    const Throws(isArgumentError);

const Matcher throwsException #

A matcher for functions that throw Exception

const Matcher throwsException = const Throws(isException);

const Matcher throwsFormatException #

A matcher for functions that throw FormatException

const Matcher throwsFormatException =
    const Throws(isFormatException);

const Matcher throwsIllegalJSRegExpException #

A matcher for functions that throw IllegalJSRegExpException

const Matcher throwsIllegalJSRegExpException =
    const Throws(isIllegalJSRegExpException);

const Matcher throwsIndexOutOfRangeException #

A matcher for functions that throw IndexOutOfRangeException

const Matcher throwsIndexOutOfRangeException =
    const Throws(isIndexOutOfRangeException);

const Matcher throwsNoSuchMethodError #

A matcher for functions that throw NoSuchMethodError

const Matcher throwsNoSuchMethodError =
    const Throws(isNoSuchMethodError);

const Matcher throwsNotImplementedException #

A matcher for functions that throw Exception

const Matcher throwsNotImplementedException =
    const Throws(isNotImplementedException);

const Matcher throwsNullPointerException #

A matcher for functions that throw NotNullPointerException

const Matcher throwsNullPointerException =
    const Throws(isNullPointerException);

const Matcher throwsUnsupportedOperationException #

A matcher for functions that throw UnsupportedOperationException

const Matcher throwsUnsupportedOperationException =
    const Throws(isUnsupportedOperationException);

Functions

Matcher matches(re) #

Returns a matcher that matches if the match argument is a string and matches the regular expression given by re. re can be a RegExp instance or a string; in the latter case it will be used to create a RegExp instance.

Matcher matches(re) => new _MatchesRegExp(re);

Matcher stringContainsInOrder(substrings) #

Returns a matcher that matches if the match argument is a string and contains a given list of substrings in relative order.

For example, stringContainsInOrder(["a", "e", "i", "o", "u"]) will match "abcdefghijklmnopqrstuvwxyz".

Matcher stringContainsInOrder(substrings) =>
    new _StringContainsInOrder(substrings);

Matcher endsWith(String suffixString) #

Returns a matcher that matches if the match argument is a string and ends with suffixString.

Matcher endsWith(String suffixString) => new _StringEndsWith(suffixString);

Matcher startsWith(String prefixString) #

Returns a matcher that matches if the match argument is a string and starts with prefixString.

Matcher startsWith(String prefixString) => new _StringStartsWith(prefixString);

String collapseWhitespace(_string) #

Utility function to collapse whitespace runs to single spaces and strip leading/trailing whitespace.

String collapseWhitespace(_string) {
  bool isWhitespace(String ch) => (' \n\r\t'.indexOf(ch) >= 0);
  StringBuffer result = new StringBuffer();
  bool skipSpace = true;
  for (var i = 0; i < _string.length; i++) {
    var character = _string[i];
    if (isWhitespace(character)) {
      if (!skipSpace) {
        result.add(' ');
        skipSpace = true;
      }
    } else {
      result.add(character);
      skipSpace = false;
    }
  }
  return result.toString().trim();
}

Matcher equalsIgnoringWhitespace(_string) #

Returns a matcher which matches if the match argument is a string and is equal to value when compared with all runs of whitespace collapsed to single spaces and leading and trailing whitespace removed.

For example, equalsIgnoringCase("hello world") will match "hello world", " hello world" and "hello world ".

Matcher equalsIgnoringWhitespace(_string) =>
    new _IsEqualIgnoringWhitespace(_string);

Matcher equalsIgnoringCase(String value) #

Returns a matcher which matches if the match argument is a string and is equal to value when compared case-insensitively.

Matcher equalsIgnoringCase(String value) => new _IsEqualIgnoringCase(value);

Matcher anyOf(arg0, [arg1 = null, arg2 = null, arg3 = null, arg4 = null, arg5 = null, arg6 = null]) #

Matches if any of the given matchers evaluate to true. The arguments can be a set of matchers as separate parameters (up to 7), or a List of matchers.

The matchers are evaluated from left to right using short-circuit evaluation, so evaluation stops as soon as a matcher returns true.

Any argument that is not a matcher is implicitly wrapped in a Matcher to check for equality.

Matcher anyOf(arg0,
               [arg1 = null,
                arg2 = null,
                arg3 = null,
                arg4 = null,
                arg5 = null,
                arg6 = null]) {
  if (arg0 is List) {
    expect(arg1, isNull);
    expect(arg2, isNull);
    expect(arg3, isNull);
    expect(arg4, isNull);
    expect(arg5, isNull);
    expect(arg6, isNull);
    for (int i = 0; i < arg0.length; i++) {
      arg0[i] = wrapMatcher(arg0[i]);
    }
    return new _AnyOf(arg0);
  } else {
    List matchers = new List();
    if (arg0 != null) {
      matchers.add(wrapMatcher(arg0));
    }
    if (arg1 != null) {
      matchers.add(wrapMatcher(arg1));
    }
    if (arg2 != null) {
      matchers.add(wrapMatcher(arg2));
    }
    if (arg3 != null) {
      matchers.add(wrapMatcher(arg3));
    }
    if (arg4 != null) {
      matchers.add(wrapMatcher(arg4));
    }
    if (arg5 != null) {
      matchers.add(wrapMatcher(arg5));
    }
    if (arg6 != null) {
      matchers.add(wrapMatcher(arg6));
    }
    return new _AnyOf(matchers);
  }
}

Matcher allOf(arg0, [arg1 = null, arg2 = null, arg3 = null, arg4 = null, arg5 = null, arg6 = null]) #

This returns a matcher that matches if all of the matchers passed as arguments (up to 7) match. Instead of passing the matchers separately they can be passed as a single List argument. Any argument that is not a matcher is implicitly wrapped in a Matcher to check for equality.

Matcher allOf(arg0,
             [arg1 = null,
              arg2 = null,
              arg3 = null,
              arg4 = null,
              arg5 = null,
              arg6 = null]) {
  if (arg0 is List) {
    expect(arg1, isNull);
    expect(arg2, isNull);
    expect(arg3, isNull);
    expect(arg4, isNull);
    expect(arg5, isNull);
    expect(arg6, isNull);
    for (int i = 0; i < arg0.length; i++) {
      arg0[i] = wrapMatcher(arg0[i]);
    }
    return new _AllOf(arg0);
  } else {
    List matchers = new List();
    if (arg0 != null) {
      matchers.add(wrapMatcher(arg0));
    }
    if (arg1 != null) {
      matchers.add(wrapMatcher(arg1));
    }
    if (arg2 != null) {
      matchers.add(wrapMatcher(arg2));
    }
    if (arg3 != null) {
      matchers.add(wrapMatcher(arg3));
    }
    if (arg4 != null) {
      matchers.add(wrapMatcher(arg4));
    }
    if (arg5 != null) {
      matchers.add(wrapMatcher(arg5));
    }
    if (arg6 != null) {
      matchers.add(wrapMatcher(arg6));
    }
    return new _AllOf(matchers);
  }
}

Matcher isNot(matcher) #

This returns a matcher that inverts matcher to its logical negation.

Matcher isNot(matcher) => new _IsNot(wrapMatcher(matcher));

Matcher inClosedOpenRange(low, high) #

Returns a matcher which matches if the match argument is greater than or equal to a low and less than high.

Matcher inClosedOpenRange(low, high) => new _InRange(low, high, true, false);

Matcher inOpenClosedRange(low, high) #

Returns a matcher which matches if the match argument is greater than low and less than or equal to high.

Matcher inOpenClosedRange(low, high) => new _InRange(low, high, false, true);

Matcher inExclusiveRange(low, high) #

Returns a matcher which matches if the match argument is greater than low and less than high.

Matcher inExclusiveRange(low, high) => new _InRange(low, high, false, false);

Matcher inInclusiveRange(low, high) #

Returns a matcher which matches if the match argument is greater than or equal to low and less than or equal to high.

Matcher inInclusiveRange(low, high) => new _InRange(low, high, true, true);

Matcher closeTo(value, delta) #

Returns a matcher which matches if the match argument is within delta of some value; i.e. if the match argument is greater than than or equal value- delta and less than or equal to value+ delta.

Matcher closeTo(value, delta) => new _IsCloseTo(value, delta);

Matcher lessThanOrEqualTo(value) #

Returns a matcher which matches if the match argument is less than or equal to the given value.

Matcher lessThanOrEqualTo(value) =>
  new _OrderingComparison(value, true, true, false,
      'a value less than or equal to');

Matcher lessThan(value) #

Returns a matcher which matches if the match argument is less than the given value.

Matcher lessThan(value) =>
  new _OrderingComparison(value, false, true, false, 'a value less than');

Matcher greaterThanOrEqualTo(value) #

Returns a matcher which matches if the match argument is greater than or equal to the given value.

Matcher greaterThanOrEqualTo(value) =>
  new _OrderingComparison(value, true, false, true,
      'a value greater than or equal to');

Matcher greaterThan(value) #

Returns a matcher which matches if the match argument is greater than the given value.

Matcher greaterThan(value) =>
  new _OrderingComparison(value, false, false, true, 'a value greater than');

Matcher neverThrew(value) #

neverThrew asserts that no matching call to a method threw a value that matched value.

Matcher neverThrew(value) =>
  new _ResultSetMatcher(Action.THROW, wrapMatcher(value), _Frequency.NONE);

Matcher sometimeThrew(value) #

sometimeThrew asserts that at least one matching call to a method threw a value that matched value.

Matcher sometimeThrew(value) =>
  new _ResultSetMatcher(Action.THROW, wrapMatcher(value), _Frequency.SOME);

Matcher alwaysThrew(value) #

alwaysThrew asserts that all matching calls to a method threw a value that matched value.

Matcher alwaysThrew(value) =>
    new _ResultSetMatcher(Action.THROW, wrapMatcher(value), _Frequency.ALL);

Matcher neverReturned(value) #

neverReturned asserts that no matching calls to a method returned a value that matched value.

Matcher neverReturned(value) =>
    new _ResultSetMatcher(Action.RETURN, wrapMatcher(value), _Frequency.NONE);

Matcher sometimeReturned(value) #

sometimeReturned asserts that at least one matching call to a method returned a value that matched value.

Matcher sometimeReturned(value) =>
    new _ResultSetMatcher(Action.RETURN, wrapMatcher(value), _Frequency.SOME);

Matcher alwaysReturned(value) #

alwaysReturned asserts that all matching calls to a method returned a value that matched value.

Matcher alwaysReturned(value) =>
    new _ResultSetMatcher(Action.RETURN, wrapMatcher(value), _Frequency.ALL);

Matcher throwing(value) #

throwing matches log entrues where the call to a method threw a value that matched value.

Matcher throwing(value) =>
    new _ResultMatcher(Action.THROW, wrapMatcher(value));

Matcher returning(value) #

returning matches log entries where the call to a method returned a value that matched value.

Matcher returning(value) =>
    new _ResultMatcher(Action.RETURN, wrapMatcher(value));

Matcher happenedAtMost(count) #

happenedAtMost matches a maximum number of calls.

Matcher happenedAtMost(count) {
  return new _TimesMatcher(0, count);
}

Matcher happenedAtLeast(count) #

happenedAtLeast matches a minimum number of calls.

Matcher happenedAtLeast(count) {
  return new _TimesMatcher(count);
}

Matcher happenedExactly(count) #

happenedExactly matches an exact number of calls.

Matcher happenedExactly(count) {
  return new _TimesMatcher(count, count);
}

CallMatcher callsTo([method, arg0 = _noArg, arg1 = _noArg, arg2 = _noArg, arg3 = _noArg, arg4 = _noArg, arg5 = _noArg, arg6 = _noArg, arg7 = _noArg, arg8 = _noArg, arg9 = _noArg]) #

Returns a CallMatcher for the specified signature. method can be null to match anything, or a literal String, a predicate Function, or a Matcher. The various arguments can be scalar values or Matchers.

CallMatcher callsTo([method,
                     arg0 = _noArg,
                     arg1 = _noArg,
                     arg2 = _noArg,
                     arg3 = _noArg,
                     arg4 = _noArg,
                     arg5 = _noArg,
                     arg6 = _noArg,
                     arg7 = _noArg,
                     arg8 = _noArg,
                     arg9 = _noArg]) {
  return new CallMatcher(method, arg0, arg1, arg2, arg3, arg4,
      arg5, arg6, arg7, arg8, arg9);
}

Matcher containsPair(key, value) #

Returns a matcher which matches maps containing the key-value pair with key => value.

Matcher containsPair(key, value) =>
    new _ContainsMapping(key, wrapMatcher(value));

Matcher containsValue(value) #

Returns a matcher which matches maps containing the given value.

Matcher containsValue(value) => new _ContainsValue(value);

Matcher completion(matcher) #

Matches a Future that completes succesfully with a value that matches matcher. Note that this creates an asynchronous expectation. The call to expect() that includes this will return immediately and execution will continue. Later, when the future completes, the actual expectation will run.

To test that a Future completes with an exception, you can use throws and throwsA.

Matcher completion(matcher) => new _Completes(wrapMatcher(matcher));

ErrorFormatter configureExpectFormatter([ErrorFormatter formatter = null]) #

Changes or resets to default the failure message formatter for expect(). formatter is a reference to the new formatter; if this is omitted or null then the failure formatter is reset to the default. The new formatter is returned; this allows custom expect handlers to easily get a reference to the default formatter.

ErrorFormatter configureExpectFormatter([ErrorFormatter formatter = null]) {
  if (formatter == null) {
    formatter = _defaultErrorFormatter;
  }
  return _assertErrorFormatter = formatter;
}

FailureHandler getOrCreateExpectFailureHandler() #

FailureHandler getOrCreateExpectFailureHandler() {
  if (_assertFailureHandler == null) {
    configureExpectFailureHandler();
  }
  return _assertFailureHandler;
}

void configureExpectFailureHandler([FailureHandler handler = null]) #

Changes or resets to the default the failure handler for expect() handler is a reference to the new handler; if this is omitted or null then the failure handler is reset to the default, which throws ExpectExceptions on expect assertion failures.

void configureExpectFailureHandler([FailureHandler handler = null]) {
  if (handler == null) {
    handler = new DefaultFailureHandler();
  }
  _assertFailureHandler = handler;
}

Matcher wrapMatcher(x) #

Takes an argument and returns an equivalent matcher. If the argument is already a matcher this does nothing, else if the argument is a function, it generates a predicate function matcher, else it generates an equals matcher.

Matcher wrapMatcher(x) {
  if (x is Matcher) {
    return x;
  } else if (x is Function) {
    return predicate(x);
  } else {
    return equals(x);
  }
}

void expect(actual, [matcher = isTrue, String reason = null, FailureHandler failureHandler = null, bool verbose = false]) #

This is the main assertion function. It asserts that actual matches the matcher. matcher is optional and defaults to isTrue, so expect can be used with a single predicate argument. reason is optional and is typically not supplied if a reasonable matcher is explicitly provided, as a reason can be generated from the matcher. If reason is included it is appended to the reason generated by the matcher.

matcher can be a value in which case it will be wrapped in an equals matcher.

If the assertion fails, then the default behavior is to throw an ExpectException, but this behavior can be changed by calling configureExpectFailureHandler and providing an alternative handler that implements the IFailureHandler interface. It is also possible to pass a failureHandler to expect as a final parameter for fine- grained control.

In some cases extra diagnostic info can be produced on failure (for example, stack traces on mismatched exceptions). To enable these, verbose should be specified as true;

expect() is a 3rd generation assertion mechanism, drawing inspiration from Hamcrest and Ladislav Thon's dart-matchers library.

See Hamcrest http://en.wikipedia.org/wiki/Hamcrest

[Hamcrest] http://code.google.com/p/hamcrest/
[dart-matchers] https://github.com/Ladicek/dart-matchers
void expect(actual, [matcher = isTrue, String reason = null,
            FailureHandler failureHandler = null,
            bool verbose = false]) {
  matcher = wrapMatcher(matcher);
  bool doesMatch;
  var matchState = new MatchState();
  try {
    doesMatch = matcher.matches(actual, matchState);
  } catch (e, trace) {
    doesMatch = false;
    if (reason == null) {
      reason = '${(e is String) ? e : e.toString()} at $trace';
    }
  }
  if (!doesMatch) {
    if (failureHandler == null) {
      failureHandler = getOrCreateExpectFailureHandler();
    }
    failureHandler.failMatch(actual, matcher, reason, matchState, verbose);
  }
}

Matcher predicate(f, [description = 'satisfies function']) #

Returns a matcher that uses an arbitrary function that returns true or false for the actual value.

Matcher predicate(f, {description: 'satisfies function'}) =>
    new _Predicate(f, description);

Matcher isIn(expected) #

Returns a matcher that matches if the match argument is in the expected value. This is the converse of contains.

Matcher isIn(expected) => new _In(expected);

Matcher contains(expected) #

Returns a matcher that matches if the match argument contains the expected value. For Strings this means substring matching; for Maps is means the map has the key, and for Collections it means the collection has a matching element. In the case of collections, expected can itself be a matcher.

Matcher contains(expected) => new _Contains(expected);

Matcher hasLength(matcher) #

Returns a matcher that matches if an object has a length property that matches matcher.

Matcher hasLength(matcher) =>
    new _HasLength(wrapMatcher(matcher));

Matcher throwsA(matcher) #

This can be used to match two kinds of objects:

  • A Function that throws an exception when called. The function cannot take any arguments. If you want to test that a function expecting arguments throws, wrap it in another zero-argument function that calls the one you want to test.

  • A Future that completes with an exception. Note that this creates an asynchronous expectation. The call to expect() that includes this will return immediately and execution will continue. Later, when the future completes, the actual expectation will run.

In both cases, when an exception is thrown, this will test that the exception object matches matcher. If matcher is not an instance of Matcher, it will implicitly be treated as equals(matcher).

Matcher throwsA(matcher) => new Throws(wrapMatcher(matcher));

Matcher equals(expected, [limit = 100]) #

Returns a matcher that does a deep recursive match. This only works with scalars, Maps and Iterables. To handle cyclic structures a recursion depth limit can be provided. The default limit is 100.

Matcher equals(expected, [limit=100]) =>
    new _DeepMatcher(expected, limit);

Matcher same(expected) #

Returns a matches that matches if the value is the same instance as object.

Matcher same(expected) => new _IsSameAs(expected);

Matcher unorderedEquals(Iterable expected) #

Returns a matcher which matches Iterables that have the same length and the same elements as expected, but not necessarily in the same order. Note that this is O(n^2) so should only be used on small objects.

Matcher unorderedEquals(Iterable expected) =>
    new _UnorderedEquals(expected);

Matcher orderedEquals(Iterable expected) #

Returns a matcher which matches Iterables that have the same length and the same elements as expected, and in the same order. This is equivalent to equals but does not recurse.

Matcher orderedEquals(Iterable expected) => new _OrderedEquals(expected);

Matcher someElement(matcher) #

Returns a matcher which matches Collections in which at least one element matches the given matcher.

Matcher someElement(matcher) => new _SomeElement(wrapMatcher(matcher));

Matcher everyElement(matcher) #

Returns a matcher which matches Collections in which all elements match the given matcher.

Matcher everyElement(matcher) => new _EveryElement(wrapMatcher(matcher));

void disableTest(int testId) #

Disable a test by ID.

void disableTest(int testId) => _setTestEnabledState(testId, false);

void enableTest(int testId) #

Enable a test by ID.

void enableTest(int testId) => _setTestEnabledState(testId, true);

void setSoloTest(int id) #

Select a solo test by ID.

void setSoloTest(int id) {
  for (var i = 0; i < _tests.length; i++) {
    if (_tests[i].id == id) {
      _soloTest = _tests[i];
      break;
    }
  }
}

ensureInitialized() #

Lazily initializes the test library if not already initialized.

ensureInitialized() {
  if (_initialized) {
    return;
  }
  _initialized = true;

  _tests = <TestCase>[];
  _testRunner = _nextBatch;
  _uncaughtErrorMessage = null;

  if (_config == null) {
    _config = new Configuration();
  }
  _config.onInit();

  if (_config.autoStart) {
    // Immediately queue the suite up. It will run after a timeout (i.e. after
    // main() has returned).
    _defer(runTests);
  }
}

void fail(String message) #

void fail(String message) {
  throw new ExpectException(message);
}

registerException(e, [trace]) #

Registers that an exception was caught for the current test.

registerException(e, [trace]) {
  _registerException(_currentTest, e, trace);
}

guardAsync(tryBody, [finallyBody, testNum = -1]) #

Run tryBody guarded in a try-catch block. If an exception is thrown, update the _currentTest status accordingly.

guardAsync(tryBody, [finallyBody, testNum = -1]) {
  if (testNum < 0) testNum = _currentTest;
  try {
    return tryBody();
  } catch (e, trace) {
    _registerException(testNum, e, trace);
  } finally {
    if (finallyBody != null) finallyBody();
  }
}

runTests() #

Runs all queued tests, one at a time.

runTests() {
  _currentTest = 0;
  _currentGroup = '';

  // If we are soloing a test, remove all the others.
  if (_soloTest != null) {
    filterTests((t) => t == _soloTest);
  }

  _config.onStart();

  _defer(() {
    _testRunner();
  });
}

void filterTests(testFilter) #

Filter the tests. testFilter can be a RegExp, a String or a predicate function. This is different to enabling/disabling tests in that it removes the tests completely.

void filterTests(testFilter) {
  var filterFunction;
  if (testFilter is String) {
    RegExp re = new RegExp(testFilter);
    filterFunction = (t) => re.hasMatch(t.description);
  } else if (testFilter is RegExp) {
    filterFunction = (t) => testFilter.hasMatch(t.description);
  } else if (testFilter is Function) {
    filterFunction = testFilter;
  }
  _tests = _tests.filter(filterFunction);
}

rerunTests() #

rerunTests() {
  _uncaughtErrorMessage = null;
  _initialized = true; // We don't want to reset the test array.
  runTests();
}

void callbackDone() #

Temporary hack: expose old API. TODO(gram) remove this when WebKit tests are working with new framework

void callbackDone() {
  _handleCallbackFunctionComplete();
}

void tearDown(Function teardownTest) #

Register a tearDown function for a test group. This function will be called after each test in the group is run. Note that if groups are nested only the most locally scoped tearDown function will be run. setUp and tearDown should be called within the group before any calls to test.

void tearDown(Function teardownTest) {
  _testTeardown = teardownTest;
}

void setUp(Function setupTest) #

Register a setUp function for a test group. This function will be called before each test in the group is run. Note that if groups are nested only the most locally scoped setUp function will be run. setUp and tearDown should be called within the group before any calls to test.

void setUp(Function setupTest) {
  _testSetup = setupTest;
}

void group(String description, void body()) #

Creates a new named group of tests. Calls to group() or test() within the body of the function passed to this will inherit this group's description.

void group(String description, void body()) {
  ensureInitialized();
  // Concatenate the new group.
  final parentGroup = _currentGroup;
  if (_currentGroup != '') {
    // Add a space.
    _currentGroup = '$_currentGroup$groupSep$description';
  } else {
    // The first group.
    _currentGroup = description;
  }

  // Groups can be nested, so we need to preserve the current
  // settings for test setup/teardown.
  Function parentSetup = _testSetup;
  Function parentTeardown = _testTeardown;

  try {
    _testSetup = null;
    _testTeardown = null;
    body();
  } catch (e, trace) {
    var stack = (trace == null) ? '' : ': ${trace.toString()}';
    _uncaughtErrorMessage = "${e.toString()}$stack";
  } finally {
    // Now that the group is over, restore the previous one.
    _currentGroup = parentGroup;
    _testSetup = parentSetup;
    _testTeardown = parentTeardown;
  }
}

Function protectAsync2(Function callback) #

Like protectAsync0 but callback should take 2 positional arguments.

Function protectAsync2(Function callback) {
  return new _SpreadArgsHelper.optionalCalls(callback).invoke2;
}

Function protectAsync1(Function callback) #

Like protectAsync0 but callback should take 1 positional argument.

Function protectAsync1(Function callback) {
  return new _SpreadArgsHelper.optionalCalls(callback).invoke1;
}

Function protectAsync0(Function callback) #

Wraps the callback in a new function and returns that function. The new function will be able to handle exceptions by directing them to the correct test. This is thus similar to expectAsync0. Use it to wrap any callbacks that might optionally be called but may never be called during the test. callback should take 0 positional arguments (named arguments are not supported).

Function protectAsync0(Function callback) {
  return new _SpreadArgsHelper.optionalCalls(callback).invoke0;
}

Function expectAsyncUntil2(Function callback, Function isDone) #

Like expectAsyncUntil0 but callback should take 2 positional arguments.

Function expectAsyncUntil2(Function callback, Function isDone) {
  return new _SpreadArgsHelper.variableCallCount(callback, isDone).invoke2;
}

Function expectAsyncUntil1(Function callback, Function isDone) #

Like expectAsyncUntil0 but callback should take 1 positional argument.

Function expectAsyncUntil1(Function callback, Function isDone) {
  return new _SpreadArgsHelper.variableCallCount(callback, isDone).invoke1;
}

Function expectAsyncUntil0(Function callback, Function isDone) #

Indicate that callback is expected to be called until isDone returns true. The unittest framework check isDone after each callback and only when it returns true will it continue with the following test. Using expectAsyncUntil0 will also ensure that errors that occur within callback are tracked and reported. callback should take 0 positional arguments (named arguments are not supported).

Function expectAsyncUntil0(Function callback, Function isDone) {
  return new _SpreadArgsHelper.variableCallCount(callback, isDone).invoke0;
}

Function expectAsync2(Function callback, [int count = 1]) #

Like expectAsync0 but callback should take 2 positional arguments.

Function expectAsync2(Function callback, [int count = 1]) {
  return new _SpreadArgsHelper.fixedCallCount(callback, count).invoke2;
}

Function expectAsync1(Function callback, [int count = 1]) #

Like expectAsync0 but callback should take 1 positional argument.

Function expectAsync1(Function callback, {int count: 1}) {
  return new _SpreadArgsHelper.fixedCallCount(callback, count).invoke1;
}

Function expectAsync0(Function callback, [int count = 1]) #

Indicate that callback is expected to be called a count number of times (by default 1). The unittest framework will wait for the callback to run the specified count times before it continues with the following test. Using expectAsync0 will also ensure that errors that occur within callback are tracked and reported. callback should take 0 positional arguments (named arguments are not supported).

Function expectAsync0(Function callback, [int count = 1]) {
  return new _SpreadArgsHelper.fixedCallCount(callback, count).invoke0;
}

void solo_test(String spec, TestFunction body) #

Creates a new test case with the given description and body. The description will include the descriptions of any surrounding group() calls.

"solo" means that this will be the only test that is run. All other tests will be skipped. This is a convenience function to let you quickly isolate a single test by adding "solo" before it to temporarily disable all other tests.

void solo_test(String spec, TestFunction body) {
  // TODO(rnystrom): Support multiple solos. If more than one test is solo-ed,
  // all of the solo-ed tests and none of the non-solo-ed ones should run.
  if (_soloTest != null) {
    throw new Exception('Only one test can be soloed right now.');
  }

  ensureInitialized();

  _soloTest = new TestCase(_tests.length + 1, _fullSpec(spec), body, 0);
  _tests.add(_soloTest);
}

void asyncTest(String spec, int callbacks, TestFunction body) #

(Deprecated) Creates a new async test case with the given description and body. The description will include the descriptions of any surrounding group() calls.

void asyncTest(String spec, int callbacks, TestFunction body) {
  ensureInitialized();

  final testCase = new TestCase(
      _tests.length + 1, _fullSpec(spec), body, callbacks);
  _tests.add(testCase);

  if (callbacks < 1) {
    testCase.error(
        'Async tests must wait for at least one callback ', '');
  }
}

void test(String spec, TestFunction body) #

Creates a new test case with the given description and body. The description will include the descriptions of any surrounding group() calls.

void test(String spec, TestFunction body) {
  ensureInitialized();
  _tests.add(new TestCase(_tests.length + 1, _fullSpec(spec), body, 0));
}

void expectThrow(function, [bool callback(exception)]) #

(Deprecated) Evaluates the function and validates that it throws an exception. If callback is provided, then it will be invoked with the thrown exception. The callback may do any validation it wants. In addition, if it returns false, that also indicates an expectation failure.

void expectThrow(function, [bool callback(exception)]) {
  bool threw = false;
  try {
    function();
  } catch (e) {
    threw = true;

    // Also let the callback look at it.
    if (callback != null) {
      var result = callback(e);

      // If the callback explicitly returned false, treat that like an
      // expectation too. (If it returns null, though, don't.)
      if (result == false) {
        fail('Exception:\n$e\ndid not match expectation.');
      }
    }
  }

  if (threw != true) fail('An expected exception was not thrown.');
}

void logMessage(String message) #

void logMessage(String message) => _config.logMessage(message);

Configuration configure(Configuration config) #

Set the Configuration used by the unittest library. Returns any previous configuration. TODO: consider deprecating in favor of a setter now we have a getter.

Configuration configure(Configuration config) {
  Configuration _oldConfig = _config;
  _config = config;
  return _oldConfig;
}

Classes

Typedefs