require “vendors/hamcrest/hamcrest-php/hamcrest/Hamcrest.php”; Include Hamcrest’s global functions Or autoload via composer.json: { “autoload”: { “files”: [ “./vendors/hamcrest/hamcrest-php/hamcrest/Hamcrest.php” ] } }
$redirectUrl = “/my_app/some_page?foo=bar”; $this->assertEquals(302, $controller->response->statusCode()); $headers = $controller->response->header(); $this->assertArrayHasKey($headers, “Location”); $this->assertEquals($headers[“Location”], $redirectUrl); Have you ever done anything like this in a test?
$redirectUrl = “/my_app/some_page?foo=bar”; assertThat($controller, redirectedToUrl($redirectUrl)); Wouldn’t it be much nicer to do this instead? assertThat() takes any value as its first argument… …and an instance of \Hamcrest \Matcher as its second argument Functions exist only as expressive factories for instantiating matchers
class Cake2ControllerRedirectMatcher extends \Hamcrest\BaseMatcher { private $url; public function __construct($url) { $this->url = $url; } public function matches($controller) { } public function describeTo(Description $description) { } }
class Cake2ControllerRedirectMatcher extends \Hamcrest\BaseMatcher { /* snip */ public function describeTo(\Hamcrest\Description $description) { $description->appendText("Controller to have status code 302 and a header location containing "); $description->appendValue($this->url); } }
class Cake2ControllerRedirectMatcher extends \Hamcrest\BaseMatcher { /* snip */ public function describeMismatch($controller, \Hamcrest\Description $description) { $description->appendText( “Controller response status code:” . $controller->response->statusCode() . “…” ); $headers = $controller->response->header(); if (!isset($headers[‘Location’])) { $this->appendText(“Location header has not been set”); } else { $description->appendText(“Location header is set as: “); $description->appendValue($headers[“Location”]); } } }
function doSomethingToAString($string) { if (!is_string($string) { throw new InvalidArgumentException(“{$string} is not a string”); } //do something } Not just for tests – reduce boilerplate function doSomethingToAString($string) { assertThat($string, is(stringValue())); //throws \Hamcrest\AssertionError //do something }
//Mockery $mock->shouldReceive(“some_method”) ->with(stringValue()); //Phake Phake::verify($mock)->some_method(stringValue()); Use with mocking libraries Both Phake and Mockery support using Hamcrest matchers for declaring expectations