Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Oct 22, 2024. It is now read-only.
/matcherPublic archive

A declarative API for specifying expectations.

License

NotificationsYou must be signed in to change notification settings

dart-archive/matcher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dart CIpub packagepackage publisher

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.

Using matcher

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

Exception matchers

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

Future Matchers

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

Stream Matchers

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.
  • emitsDone matches 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().

Best Practices

Prefer semantically meaningful matchers to comparing derived values

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>

Prefer TypeMatcher to predicate if the match can fail in multiple ways

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

Stars

Watchers

Forks

Packages

No packages published

Contributors27

Languages


[8]ページ先頭

©2009-2025 Movatter.jp