Cette page illustre ce que sont les Matchers JUnit4 ainsi que leur utilisation.
Les Matchers permettent d'aboutir à des tests écrits de manière très lisibles à la façon des Fluent Interface introduites (il me semble) par Monsieur Martin Fowler.
Utilisation des matchers :
Exemple de matchers de base
Overview des matchers fournis par Harmcrest :
Core
anything - always matches, useful if you don't care what the object under test is
describedAs - decorator to adding custom failure description
is - decorator to improve readability - see "Sugar", below
Logical
allOf - matches if all matchers match, short circuits (like Java &&)
anyOf - matches if any matchers match, short circuits (like Java ||)
not - matches if the wrapped matcher doesn't match and vice versa
Object
equalTo - test object equality using Object.equals
hasToString - test Object.toString
instanceOf, isCompatibleType - test type
notNullValue, nullValue - test for null
sameInstance - test object identity
Beans
hasProperty - test JavaBeans properties
Collections
array - test an array's elements against an array of matchers
hasEntry, hasKey, hasValue - test a map contains an entry, key or value
hasItem, hasItems - test a collection contains elements
hasItemInArray - test an array contains an element
Number
closeTo - test floating point values are close to a given value
greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo - test ordering
Text
equalToIgnoringCase - test string equality ignoring case
equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace
containsString, endsWith, startsWith - test string matching
Définition de matcher :
Définition d'un matcher
La méthode describeTo permet d'obtenir un message clair lorsque l'assertion est incorrecte. Si, dans notre exemple précédent, nous changeons le paramètre à une taille de 4 pour la méthode de test hasItemWithStringLengthMatcher(), alors l'assertion devient fausse et l'exception retournée est la suivante