-
Notifications
You must be signed in to change notification settings - Fork 24
Constraints
This is a tutorial for using https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/Constraint.
Constraints are derived from Hamcrest matchers. Hamcrest is a framework for creating matchers, allowing match rules to be defined declaratively (see). In PHPUnit the two most common usages of constraints are:
- Creating new assertions with
assertThat- Advanced matching of parameters in Mock Objects
This constraint requires that the actual array contains at least one of each of the expected items.
Example: $object = $this->getMock('SomeClass') ->expects($this->any()) ->method('doSomething') ->with(new PHPUnit_Extensions_Constraint_HasItems(array(1, 2, 3)));
... // This will pass because we passed in an array that contains at least a 1, a 2, and a 3 $object->doSomething(array(4, 3, 2, 1)); // This will fail because we passed in an array that was missing a 1 $object->doSomething(array(3, 2, 0));
More Examples: https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/Constraint/HasItemsTest.php
This constraint requires that the size of the actual array is the same as the expected
Example: $object = $this->getMock('SomeClass') ->expects($this->any()) ->method('doSomething') ->with(new PHPUnit_Extensions_Constraint_HasItems(array(1, 2, 3)));
... // This will pass because we passed in an array of size 3 $object->doSomething(array(4, 5, 6)); // This will fail because we passed in array that is not of size 3 $object->doSomething(array(1, 1, 2, 3));
More Examples: https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/Constraint/SameSize.php
This constraint allows verifying that the actual content of the string is as expected without needing to match leading or trailing whitespace, or having to get tabs and newlines correct.
Example: $object = $this->getMock('SomeClass') ->expects($this->any()) ->method('doSomething') ->with(new PHPUnit_Extensions_Constraint_HasItems("spaces do not matter"));
... // This will pass because the string after reducing white space are "spaces do not matter" $object->doSomething("spaces\ndo\tnot matter "); // This will fail because this string is NOT equivalent to "spaces do not matter" $object->doSomething("but the not whitespace characters do!");
More Examples: https://github.com/etsy/phpunit-extensions/tree/master/PHPUnit/Extensions/Constraint/StringMatchIgnoreWhitespace.php