Replace raw PHPUnit assertEquals calls with readable assertThat expressions that produce better error messages on failure.
Write tests that check arrays contain a specific item, have a certain size, or match a pattern in one fluent line.
Combine multiple matchers in a single assertion to verify a value satisfies two conditions at once.
Add hamcrest-php matchers to a legacy PHPUnit test suite to improve readability without changing existing test logic.
Global shorthand functions require an explicit registration call before they are available in tests.
Hamcrest-PHP is a library for PHP developers who write automated tests. Its job is to give you a readable way to describe what a value should look like before you check it. Instead of writing a raw comparison in your test, you write something like "assertThat($result, equalTo(true))" or "assertThat($list, hasItemInArray(4))", and the library checks whether the value matches that description and produces a clear error message when it does not. The library is a direct port of Hamcrest, which originally came from the Java world and has since been translated into many languages. This is the official PHP version. The translation is fairly literal, though a handful of Java features that do not exist in PHP were left out, and a few method names were adjusted to avoid conflicts with PHP reserved words. For example, the Java method called "and" becomes "andAlso" here because "and" is a keyword in PHP. The matchers cover a wide range of situations. You can check arrays for specific values, keys, sizes, or ordering. You can check whether a variable is null, what type it is, or whether it is an instance of a particular class. There are string matchers for checking substrings, case-insensitive equality, and pattern matching. Number matchers handle greater-than, less-than, and close-to comparisons. You can also combine matchers, so a single assertion can check that a value satisfies two conditions at once, or that it satisfies at least one of several conditions. Installation is done through Composer, which is the standard PHP dependency manager. After installing, you can call matchers either through a namespaced class or through shorter global proxy functions. The global functions need to be registered explicitly with one setup call before they are available. The library is commonly used alongside PHPUnit, the most widely used PHP testing framework. It slots in as an alternative to PHPUnit's own assertion style, and many PHP projects pull it in as a dependency simply because other testing tools require it.
← hamcrest on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.