Laravel best approach for testing HTTP requests

  laravel, php, testing

Let’s say I have a Client class that uses the Laravel HTTP Client:

class BestBuyClient
    public function checkAvailability($stockId): StockStatus
        ////hard-coded url to simplify the example
        $url = "{$stockId}"; 
        $results = HTTP::get($url)->json();

        return new StockStatus(
            $results['onlineAvailability'] ?? '',
            $results['salePrice'] ?? ''

Then, let’s say I have a service class that uses that client class:

class TrackStockService
    protected $bestBuyClient;

    public function __construct(BestBuyClient $bestBuyClient)
        $this->bestBuyClient = $bestBuyClient;

    protected function refreshStock()
        $availability = $this->bestBuyClient->checkAvailability(1); //hard-coded Id to simplify the example
        //do additional operations with the returned response


What would be the best approach to test the Service class? I’m thinking of two solutions:

  1. Fake the HTTP requests using the Laravel feature
  2. Mock the bestBuyClient in the service and return a fake object with dummy data

Which one of these is a better approach and why?

Source: Laravel

Leave a Reply