Dart API Referenceunittest

unittest library

A library for writing dart unit tests.

To import this library, specify the relative path to lib/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/lib/unittest/unitest.dart');
main() {
  test('this is a test', () {
    int x = 2 + 3;
    expect(x, equals(5));
  });
}

Multiple tests:

#import('path-to-dart/lib/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/lib/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/lib/unittest/unitest.dart');
#import('dart:dom_deprecated');
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/lib/unittest/unitest.dart');
#import('dart:dom_deprecated');
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);
  });

Methods

Code 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);
  }
}

Code 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);

Code 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);

Code 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);
  }
}

Code 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 ', '');
  }
}

Code void callbackDone() #

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

void callbackDone() {
  _handleCallbackFunctionComplete();
}

Code 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);
}

Code 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);

Code 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();
}

Code 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));

Code Configuration configure(Configuration config) #

Set the Configuration used by the unittest library. Returns any previous configuration.

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

Code 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;
}

Code 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;
}

Code 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);

Code 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));

Code Matcher containsValue(value) #

Returns a matcher which matches maps containing the given value.

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

Code void disableTest(int testId) #

Disable a test by ID.

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

Code void enableTest(int testId) #

Enable a test by ID.

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

Code 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);

Code 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);
  }
}

Code 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);

Code 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);

Code 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);

Code Matcher everyElement(matcher) #

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

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

Code 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 (var e, var 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);
  }
}

Code 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;
}

Code 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;
}

Code 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;
}

Code 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;
}

Code 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;
}

Code 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;
}

Code 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 (var 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.');
}

Code FailureHandler getOrCreateExpectFailureHandler() #

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

Code 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');

Code 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');

Code 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 $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();
  } finally {
    // Now that the group is over, restore the previous one.
    _currentGroup = parentGroup;
    _testSetup = parentSetup;
    _testTeardown = parentTeardown;
  }
}

Code 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 (var e, var trace) {
    registerException(testNum, e, trace);
  } finally {
    if (finallyBody != null) finallyBody();
  }
}

Code Matcher happenedAtLeast(count) #

happenedAtLeast matches a minimum number of calls.

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

Code Matcher happenedAtMost(count) #

happenedAtMost matches a maximum number of calls.

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

Code Matcher happenedExactly(count) #

happenedExactly matches an exact number of calls.

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

Code 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));

Code 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);

Code 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);

Code 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);

Code 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);

Code 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);

Code Matcher isNot(matcher) #

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

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

Code 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');

Code 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');

Code void logMessage(String message) #

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

Code 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);

Code 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);

Code 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);

Code 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);

Code 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);

Code 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;
}

Code Function protectAsync1(Function callback) #

Like protectAsync0 but callback should take 1 positional argument.

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

Code Function protectAsync2(Function callback) #

Like protectAsync0 but callback should take 2 positional arguments.

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

Code registerException(testNum, e, [trace]) #

Registers that an exception was caught for the current test.

registerException(testNum, e, [trace]) {
  trace = trace == null ? '' : trace.toString();
  if (_tests[testNum].result == null) {
    String message = (e is ExpectException) ? e.message : 'Caught $e';
    _tests[testNum].fail(message, trace);
  } else {
    _tests[testNum].error('Caught $e', trace);
  }
  if (testNum == _currentTest) {
    _nextTestCase();
  }
}

Code void reportTestError(String msg, String trace) #

Utility function that can be used to notify the test framework that an error was caught outside of this library.

void reportTestError(String msg, String trace) {
 if (_currentTest < _tests.length) {
    final testCase = _tests[_currentTest];
    testCase.error(msg, trace);
    if (testCase.callbackFunctionsOutstanding > 0) {
      _nextTestCase();
    }
  } else {
    _uncaughtErrorMessage = "$msg: $trace";
  }
}

Code rerunTests() #

rerunTests() {
  _uncaughtErrorMessage = null;
  runTests();
}

Code 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));

Code 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) {
    _tests = _tests.filter((t) => t == _soloTest);
  }

  if (filter != null) {
    RegExp re = new RegExp(filter);
    _tests = _tests.filter((t) => re.hasMatch(t.description));
  }

  _config.onStart();

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

Code Matcher same(expected) #

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

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

Code 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;
    }
  }
}

Code 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;
}

Code 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);
}

Code 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));

Code 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);

Code 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);

Code 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);

Code 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);

Code 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;
}

Code 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));
}

Code get testCases() #

Get the list of tests.

get testCases() => _tests;

Code 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));

Code 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));

Code 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);

Code 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);
  }
}

Fields

Code final Matcher anything #

A matcher that matches any value.

final Matcher anything = const _IsAnything();

Code 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);

Code String filter #

The regexp pattern filter which constrains which tests to run based on their descriptions.

String filter = null;

Code final Matcher happenedAtLeastOnce #

happenedAtLeastOnce matches one or more calls.

final Matcher happenedAtLeastOnce = const _TimesMatcher(1);

Code final Matcher happenedAtMostOnce #

happenedAtMostOnce matches zero or one call.

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

Code final Matcher happenedOnce #

happenedOnce matches exactly one call.

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

Code final isBadNumberFormatException #

A matcher for BadNumberFormatExceptions.

final isBadNumberFormatException = const _BadNumberFormatException();

Code final Matcher isEmpty #

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

final Matcher isEmpty = const _Empty();

Code final isException #

A matcher for Exceptions.

final isException = const _Exception();

Code final Matcher isFalse #

A matcher that matches anything except the Boolean value true.

final Matcher isFalse = const _IsFalse();

Code final isIllegalArgumentException #

A matcher for IllegalArgumentExceptions.

final isIllegalArgumentException = const _IllegalArgumentException();

Code final isIllegalJSRegExpException #

A matcher for IllegalJSRegExpExceptions.

final isIllegalJSRegExpException = const _IllegalJSRegExpException();

Code final isIndexOutOfRangeException #

A matcher for IndexOutOfRangeExceptions.

final isIndexOutOfRangeException = const _IndexOutOfRangeException();

Code final Matcher isNegative #

A matcher which matches if the match argument is negative.

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

Code final isNoSuchMethodException #

A matcher for NoSuchMethodExceptions.

final isNoSuchMethodException = const _NoSuchMethodException();

Code final Matcher isNonNegative #

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

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

Code final Matcher isNonPositive #

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

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

Code final Matcher isNonZero #

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

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

Code final isNotImplementedException #

A matcher for NotImplementedExceptions.

final isNotImplementedException = const _NotImplementedException();

Code final Matcher isNotNull #

A matcher that matches any non-null value.

final Matcher isNotNull = const _IsNotNull();

Code final Matcher isNull #

A matcher that matches any null value.

final Matcher isNull = const _IsNull();

Code final isNullPointerException #

A matcher for NullPointerExceptions.

final isNullPointerException = const _NullPointerException();

Code final Matcher isPositive #

A matcher which matches if the match argument is positive.

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

Code final Matcher isTrue #

A matcher that matches the Boolean value true.

final Matcher isTrue = const _IsTrue();

Code final isUnsupportedOperationException #

A matcher for UnsupportedOperationExceptions.

final isUnsupportedOperationException = const _UnsupportedOperationException();

Code final Matcher isZero #

A matcher which matches if the match argument is zero.

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

Code final Matcher neverHappened #

neverHappened matches zero calls.

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

Code final 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.

final Matcher returnsNormally = const _ReturnsNormally();

Code LogEntryList sharedLog #

The shared log used for named mocks.

LogEntryList sharedLog = null;

Code final 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.

final Matcher throws = const _Throws();

Code final Matcher throwsBadNumberFormatException #

A matcher for functions that throw BadNumberFormatException

final Matcher throwsBadNumberFormatException =
    const _Throws(isBadNumberFormatException);

Code final Matcher throwsException #

A matcher for functions that throw Exception

final Matcher throwsException = const _Throws(isException);

Code final Matcher throwsIllegalArgumentException #

A matcher for functions that throw IllegalArgumentException

final Matcher throwsIllegalArgumentException =
    const _Throws(isIllegalArgumentException);

Code final Matcher throwsIllegalJSRegExpException #

A matcher for functions that throw IllegalJSRegExpException

final Matcher throwsIllegalJSRegExpException =
    const _Throws(isIllegalJSRegExpException);

Code final Matcher throwsIndexOutOfRangeException #

A matcher for functions that throw IndexOutOfRangeException

final Matcher throwsIndexOutOfRangeException =
    const _Throws(isIndexOutOfRangeException);

Code final Matcher throwsNoSuchMethodException #

A matcher for functions that throw NoSuchMethodException

final Matcher throwsNoSuchMethodException =
    const _Throws(isNoSuchMethodException);

Code final Matcher throwsNotImplementedException #

A matcher for functions that throw Exception

final Matcher throwsNotImplementedException =
    const _Throws(isNotImplementedException);

Code final Matcher throwsNullPointerException #

A matcher for functions that throw NotNullPointerException

final Matcher throwsNullPointerException =
    const _Throws(isNullPointerException);

Code final Matcher throwsUnsupportedOperationException #

A matcher for functions that throw UnsupportedOperationException

final Matcher throwsUnsupportedOperationException =
    const _Throws(isUnsupportedOperationException);

Classes

Interfaces