To create custom PHPUnit constraints for specialized assertions, follow these steps:
PHPUnit\Framework\Constraint\Constraint
class.use PHPUnit\Framework\Constraint\Constraint;
class MyCustomConstraint extends Constraint
{
// Implement your constraint logic here
}
matches()
method within your custom constraint. This method should contain the logic for evaluating whether the constraint is fulfilled or not.class MyCustomConstraint extends Constraint
{
// ...
public function matches($other): bool
{
// Implement your constraint logic here
// Return true if the constraint is fulfilled, otherwise false
return $isFulfilled;
}
}
toString()
method to display a string representation of the constraint that you can use in assertion failure messages.class MyCustomConstraint extends Constraint
{
// ...
protected function toString(): string
{
return 'description of your constraint';
}
}
additionalFailureDescription()
method to provide additional failure information in assertion failure messages.class MyCustomConstraint extends Constraint
{
// ...
protected function additionalFailureDescription($other): string
{
// Implement additional failure description logic here
return 'additional failure description';
}
}
failureDescription()
method to customize the failure description that is displayed in assertion failure messages.class MyCustomConstraint extends Constraint
{
// ...
public function failureDescription($other): string
{
return sprintf(
'additional prefix %s additional suffix',
$this->toString()
);
}
}
count()
method if your constraint supports countable assertions, such as assertCount()
.class MyCustomConstraint extends Constraint implements \Countable
{
// ...
public function count(): int
{
// Implement count logic here
// Return the count as an integer
return $count;
}
}
assertThat()
method.public function testMyCustomConstraint()
{
$this->assertThat($value, new MyCustomConstraint());
}
That's it! Your custom PHPUnit constraint is now ready for use in your tests with specialized assertions.