Dart Documentationmatcher

matcher library

The matcher library provides a 3rd generation assertion mechanism, drawing inspiration from Hamcrest.

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, '')

const isArgumentError #

A matcher for ArgumentErrors.

const isArgumentError = const _ArgumentError()

const Matcher isEmpty #

Returns a matcher that matches empty strings, maps or iterables (including 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 isList #

A matcher for List types.

const isList = const _IsList()

const isMap #

A matcher for Map types.

const isMap = const _IsMap()

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 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 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 isRangeError #

A matcher for RangeErrors.

const isRangeError = const _RangeError()

const isStateError #

A matcher for StateErrors.

const isStateError = const _StateError()

const Matcher isTrue #

A matcher that matches the Boolean value true.

const Matcher isTrue = const _IsTrue()

const isUnimplementedError #

A matcher for UnimplementedErrors.

const isUnimplementedError = const _UnimplementedError()

const isUnsupportedError #

A matcher for UnsupportedError.

const isUnsupportedError = const _UnsupportedError()

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 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()

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 throwsNoSuchMethodError #

A matcher for functions that throw NoSuchMethodError.

const Matcher throwsNoSuchMethodError =
   const Throws(isNoSuchMethodError)

const Matcher throwsRangeError #

A matcher for functions that throw RangeError.

const Matcher throwsRangeError =
   const Throws(isRangeError)

const Matcher throwsStateError #

A matcher for functions that throw StateError.

const Matcher throwsStateError =
   const Throws(isStateError)

const Matcher throwsUnimplementedError #

A matcher for functions that throw Exception.

const Matcher throwsUnimplementedError =
   const Throws(isUnimplementedError)

const Matcher throwsUnsupportedError #

A matcher for functions that throw UnsupportedError.

const Matcher throwsUnsupportedError = const Throws(isUnsupportedError)

Function wrapAsync #

Some matchers, like those for Futures and exception testing, can fail in asynchronous sections, and throw exceptions. A user of this library will typically want to catch and handle such exceptions. The wrapAsync property is a function that can wrap callbacks used by these Matchers so that they can be used safely. For example, the unittest library will set this to be expectAsync1. By default this is an identity function.

Function wrapAsync = (f, [id]) => f

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.write(' ');
       skipSpace = true;
     }
   } else {
     result.write(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 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, [String id = '']) #

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.

id is an optional tag that can be used to identify the completion matcher in error messages.

Matcher completion(matcher, [String id = '']) =>
   new _Completes(wrapMatcher(matcher), id);

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 TestFailures 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 fail(String message, {FailureHandler failureHandler}) #

void fail(String message, {FailureHandler failureHandler}) {
 if (failureHandler == null) {
   failureHandler = getOrCreateExpectFailureHandler();
 }
 failureHandler.fail(message);
}

void expect(actual, matcher, {String reason, FailureHandler failureHandler, bool verbose: false}) #

This is the main assertion function. It asserts that actual matches the matcher. reason is optional and is typically not supplied, as a reason is 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 a TestFailure, 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;

void expect(actual, matcher, {String reason, FailureHandler failureHandler,
           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(Function f, [description = 'satisfies function']) #

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

expect(v, predicate((x) => ((x % 2) == 0), "is even"))
Matcher predicate(Function 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 it means the map has the key, and for Iterables (including Collections) it means the iterable has a matching element. In the case of iterables, 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));

Abstract Classes

Classes

Typedefs