Method Assertions

Just like with properties, 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);

Just like with returnValue(), throwException() will call your method and then capture any exceptions it throws so that you can write assertion about the exception object. If your method does not throw an exception, throwException() will fail the test for you.

To inspect the exception further, you can drill into it 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);

Invokable Objects

If your subject is an object with an __invoke() magic method, you can write assertions about its return value or exceptions just like with other methods. Simply use returnValue() or throwException() after passing your subject to verify() and BeBat/Verify will invoke your object itself:

verify($subject)->will()->returnValue()->identicalTo('return value of __invoke()');

You can supply parameters for your subject using with() just like other methods:

verify($subject)
    ->with('invalid parameter')->will()
        ->throwException()->instanceOf(InvalidArgumentException::class)
    ->with('correct parameter')->will()
        ->returnValue()->identicalTo('correct parameter value');