- Notifications
You must be signed in to change notification settings - Fork37
A declarative API for specifying expectations.
License
dart-archive/matcher
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Important
This repo has moved tohttps://github.com/dart-lang/test/tree/master/pkgs/matcher
Support for specifying test expectations, such as for unit tests.
The matcher library provides a third-generation assertion mechanism, drawinginspiration fromHamcrest.
For more information on testing, seeUnit Testing with Dart.
Expectations start with a call toexpect() orexpectAsync().
Any matchers package can be used withexpect() to docomplex validations:
import'package:test/test.dart';voidmain() {test('.split() splits the string on the delimiter', () {expect('foo,bar,baz',allOf([contains('foo'),isNot(startsWith('bar')),endsWith('baz') ])); });}
If a non-matcher value is passed, it will be wrapped withequals().
You can also test exceptions with thethrowsA() function or a matcher suchasthrowsFormatException:
import'package:test/test.dart';voidmain() {test('.parse() fails on invalid input', () {expect(()=>int.parse('X'), throwsFormatException); });}
There are a number of useful functions and matchers for more advancedasynchrony. Thecompletion() matcher can be used to testFutures; itensures that the test doesn't finish until theFuture completes, and runs amatcher against thatFuture's value.
import'dart:async';import'package:test/test.dart';voidmain() {test('Future.value() returns the value', () {expect(Future.value(10),completion(equals(10))); });}
ThethrowsA() matcher and the variousthrowsExceptionType matchers workwith both synchronous callbacks and asynchronousFutures. They ensure that aparticular type of exception is thrown:
import'dart:async';import'package:test/test.dart';voidmain() {test('Future.error() throws the error', () {expect(Future.error('oh no'),throwsA(equals('oh no')));expect(Future.error(StateError('bad state')), throwsStateError); });}
TheexpectAsync() function wraps another function and has two jobs. First,it asserts that the wrapped function is called a certain number of times, andwill cause the test to fail if it's called too often; second, it keeps the testfrom finishing until the function is called the requisite number of times.
import'dart:async';import'package:test/test.dart';voidmain() {test('Stream.fromIterable() emits the values in the iterable', () {var stream=Stream.fromIterable([1,2,3]); stream.listen(expectAsync1((number) {expect(number,inInclusiveRange(1,3)); }, count:3)); });}
Thetest package provides a suite of powerful matchers for dealing withasynchronous streams. They're expressive and composable, and make iteasy to write complex expectations about the values emitted by a stream. Forexample:
import'dart:async';import'package:test/test.dart';voidmain() {test('process emits status messages', () {// Dummy data to mimic something that might be emitted by a process.var stdoutLines=Stream.fromIterable(['Ready.','Loading took 150ms.','Succeeded!' ]);expect(stdoutLines,emitsInOrder([// Values match individual events.'Ready.',// Matchers also run against individual events.startsWith('Loading took'),// Stream matchers can be nested. This asserts that one of two events are// emitted after the "Loading took" line.emitsAnyOf(['Succeeded!','Failed!']),// By default, more events are allowed after the matcher finishes// matching. This asserts instead that the stream emits a done event and// nothing else. emitsDone ])); });}
A stream matcher can also match theasync package'sStreamQueue class,which allows events to be requested from a stream rather than pushed to theconsumer. The matcher will consume the matched events, but leave the rest of thequeue alone so that it can still be used by the test, unlike a normalStreamwhich can only have one subscriber. For example:
import'dart:async';import'package:async/async.dart';import'package:test/test.dart';voidmain() {test('process emits a WebSocket URL', ()async {// Wrap the Stream in a StreamQueue so that we can request events.var stdout=StreamQueue(Stream.fromIterable(['WebSocket URL:','ws://localhost:1234/','Waiting for connection...' ]));// Ignore lines from the process until it's about to emit the URL.awaitexpectLater(stdout,emitsThrough('WebSocket URL:'));// Parse the next line as a URL.var url=Uri.parse(await stdout.next);expect(url.host,equals('localhost'));// You can match against the same StreamQueue multiple times.awaitexpectLater(stdout,emits('Waiting for connection...')); });}
The following built-in stream matchers are available:
emits()matches a single data event.emitsError()matches a single error event.emitsDonematches a single done event.mayEmit()consumes events if they match an inner matcher, withoutrequiring them to match.mayEmitMultiple()works likemayEmit(), but it matches events againstthe matcher as many times as possible.emitsAnyOf()consumes events matching one (or more) of several possiblematchers.emitsInOrder()consumes events matching multiple matchers in a row.emitsInAnyOrder()works likeemitsInOrder(), but it allows thematchers to match in any order.neverEmits()matches a stream that finisheswithout matching an innermatcher.
You can also define your own custom stream matchers withStreamMatcher().
Matchers which have knowledge of the semantics that are tested are able to emitmore meaningful messages which don't require reading test source to understandwhy the test failed. For instance compare the failures betweenexpect(someList.length, 1), andexpect(someList, hasLength(1)):
// expect(someList.length, 1); Expected: <1> Actual: <2>// expect(someList, hasLength(1)); Expected: an object with length of <1> Actual: ['expected value', 'unexpected value'] Which: has length of <2>Thepredicate utility is a convenient shortcut for testing an arbitrary(synchronous) property of a value, but it discards context and failures areopaque. Different failure modes cannot be distinguished in the output which isdetermined by a single "description" argument. UsingisA<SomeType>() and theTypeMatcher.having API to extract and test derived properties in a structuredway brings the context of that structure through to failure messages, sofailures for different reasons will have distinguishable and actionable failuremessages.
About
A declarative API for specifying expectations.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.