Описание тега matcher
The most basic matcher is a function from an object to boolean
, where the return value denotes whether the argument matches the description represented by the matcher.
Apart from doing the actual matching matchers most of the time also provide some information about why a matcher did not match, and they can be combined using methods or functions, that take matchers as an argument and return new matchers (see the example below).
Matchers allow expectations to be written in an internal DSL. For example using Hamcrest and JUnit assertions can be written like this:
assertThat("nuts", biscuit.nutCount(), allOf(greaterThan(3), evenNumber()));
This is relatively easy to understand, even without knowing how it exactly works, and it will provide failure messages that explain the reason why the assertion failed. In the above example allOf()
, greaterThan()
and evenNumber()
are all methods returning matchers.
Matchers are also used in other libraries, for example mock libraries use matchers in order to formulate expectations about calls to mocks, stubs or spies, like in the following example with Mockito.
when(mockedList.get(anyInt())).thenReturn("element");
Here anyInt()
returns a matcher that matches any Integer
or int
.