Improve Your Productivity While Utilizing Laravel Mocks

Improve Your Productivity While Utilizing Laravel Mocks

Laravel has numerous test helpers and mocks within the framework, which is fantastic. However, I see other engineers getting caught up on debugging issues when they arise.

The Laravel docs show this as an example

Queue::assertPushed(function (ShipOrder $job) use ($order) {
    return $job->order->id === $order->id;
});

Straightforward, right? We're trying to ensure that the ShipOrder job was pushed to the queue and the order IDs matched.

What happens when the IDs do not match, or something else happens? We get the following error

Failed asserting that false is true.

Which is not that helpful. We know that the job wasn't pushed, but was it an error with the IDs matching, or something else? This issue gets exacerbated when you have multiple conditions that need to pass.

Queue::assertPushed(function (ShipOrder $job) use ($order) {
    return $job->order->id === $order->id
        && $job->order->second === $order->second
        && $job->order->third === $order->third
        && $job->order->fourth === $order->fourth;
});

Now, if any of those conditions fail, then we'll still get the same PHPUnit error message.

Failed asserting that false is true.

There is no way to know which condition failed easily. You can remove one condition at a time, but that's a time-consuming process. There's a better way.

Instead of using chained conditions, we can use assertions for each of the comparisons. Then we can manually return true if all of the conditions are true.

Queue::assertPushed(function (ShipOrder $job) use ($order) {
    $this->assertSame($job->order->id, $order->id);
    $this->assertSame($job->order->second, $order->second);
    $this->assertSame($job->order->third, $order->third);
    $this->assertSame($job->order->fourth, $order->fourth);

    return true;
});

Now, if any of these assertions fail, PHPUnit will be able to narrow in on the exact line number that failed - making it quicker to debug and getting you on your way.

Failed asserting that X is identical to Y

# ---

Failed asserting that 456 is identical to 123.
 /tests/PathToFileTest.php:62

In conclusion, by using assertions for each comparison, you can quickly pinpoint and resolve issues in your code. Leveraging Laravel mocks effectively can significantly improve your productivity as a developer.


Don't forget to share this article with your fellow developers to help them optimize their Laravel testing experience!