Extending

BeBat/Verify includes almost all the assertions built into PHPUnit, and all the ones from bebat/filesystem-assertions, but there may be additional assertions you need in your project. Depending on the number and complexity of assertions you want to add, BeBat/Verify includes two ways for you to extend it and add your own assertions.

Custom Constraint

Constraints are the building blocks for both PHPUnit and BeBat/Verify’s assertions. It is possible to write your own constraints by extending PHPUnit’s Constraint class.

To assert a constraint, pass it to BeBat/Verify’s constraint() method after a conjunction, just like any other assertion. For example, if you had the package coduo/php-matcher installed:

use Coduo\PHPMatcher\PHPUnit\PHPMatcherConstraint;

use function BeBat\Verify\verify;

verify('{"name": "Norbert"}')->has()
    ->constraint(new PHPMatcherConstraint('{"name": "@string@"}'));

Custom Verifier

Using a custom constraint works well if your assertion is a one off and relatively simple. For anything more complicated though you should create your own verifier class. A verifier extends BeBat\Verify\API\Base and includes one or more assertion methods.

To use your verifier in an assertion chain, pass its class name to withVerifier(). BeBat/Verify will instantiate your verifier and pass it the subject and its name. If the constructor requires any additional arguments they can be passed to withVerifier().

The withVerifier() method can also be used to switch between the value and file verifiers. For example, suppose you were testing a method that created a file and returned its path. If you wanted to write assertions about both the file contents and its name, you could do so by switching between verifiers with the withVerifier() method:

use BeBat\Verify\API\File;

// ...

verify($subject->writeFile())->will()->endWith('.log')      // assertion about the file path
    ->withVerifier(File::class)->contain('My Log Message'); // assertion about the file contents

For more details about writing your own verifier, see its API documentation.