Method Assertions

Just like with attributes, assertions can be made about an object’s methods by adding the method call after verify(). You can write assertions about either a method’s return value or an exception that the method throws.

Return Values

A simple example might look like:

verify($calculator)->add(2, 3)->will()->returnValue()->identicalTo(5);

In returnValue(), BeBat/Verify will call add() on the $calculator object, passing it 2 and 3, and then cache its result internally. This means you can write multiple assertions about the return value, just like other verifiers, without the method needing to be called again.

If your method name conflicts with part of the verifier API, you can use method() and with() to explicitly set a method name and arguments:

verify(new ArrayObject([]))
    ->method('empty')->will()->returnValue()->true()
    ->method('count')->will()->returnValue()->identicalTo(0);

The with() method can also be used to set up multiple example arguments for a single method:

verify($calculator)->add()
    ->with(1, $someValue)->will()->returnValue()->greaterThan($someValue)
    ->with(0, $someValue)->will()->returnValue()->identicalTo($someValue)
    ->with(-1, $someValue)->will()->returnValue()->lessThan($someValue);

Exceptions

If you need to test an exception thrown by your method, you may do so with throwException() like so:

verify($calculator)->divide($someValue, 0)
    ->will()->throwException()->instanceOf(DivideByZeroException::class);

You can drill into more detail of your exception by using the withMessage() and withCode() methods:

verify($calculator)->add(1, 'two')
    ->will()->throwException()->instanceOf(InvalidArgumentException::class)
    ->withMessage()->startWith('Invalid argument passed')
    ->withCode()->identicalTo(2);