darmatch 0.2.0 darmatch: ^0.2.0 copied to clipboard
Standalone matchers library.
Darmatch #
Darmatch is a standalone library of matchers in Dart. Note: it used to be called Dart Matchers. It is heavily inspired by Hamcrest.
Matchers #
Matcher is a declarative description of certain condition. For example,
var adult = greaterThanOrEqual(18);
creates a variable that can be later used to check if someone's age is > 18
.
The variable implements the Matcher
interface, so there are two basic
operations you can do: check if some value matches
and get a description
of the condition.
if (!adult.matches(someInput)) {
throw new RestrictedZoneException("Your age must be ${adult.description}");
}
Matchers are usually used in unit testing: Dart's own unittest
library has
a matchers framework built-in, and my Detester
testing framework supports Darmatch natively. But they can also be used for
working with collections (my Deequery
library treats them in the same way as normal predicates) and other things.
Preconditions #
One of the other areas where matchers can be useful is precondition checking.
Darmatch has a tiny library for preconditions that only contains one function:
checkThat
. Use it like this:
addNumbers(num1, num2) {
checkThat(num1, isNotNull(), 'must not be null');
checkThat(num2, isNotNull(), 'must not be null');
return num1 + num2;
}
Note that the message is not mandatory; if you don't supply one, default matcher description will be used.
If the check is successful, checkThat
returns the original object. This
can be useful e.g. when writing constructors:
class SomeClass {
String s;
SomeClass(String s) {
this.s = checkThat(s, not(empty()));
}
}