Source: paulund.co.uk

How To Mock Classes In PHP
Testing is an important area of any application, when you write some code you need to make sure that all your logic is working correctly. In this tutorial we're going to learn when and how you will mock a classes in your php tests. Imagine we have a class to get information from a thrid party api, such as getting tweets for a specific user like below.

$twitterMock->shouldReceive('getTweets')->andReturn([[ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ]]); This makes sure we can guarantee what we get back from the API. shouldReceive('getTweets')->andReturn([[ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ]]); // When $latestTweets = new LatestTweets($twitterMock); // Then $this->assertCount(3, $latestTweets->tweets()); } /** @test */ public function it_only_returns_5_tweets_from_twitter_client() { // Given $faker = app(Generator::class); $twitterMock = \Mockery::mock(TwitterClient::class); $twitterMock->shouldReceive('getTweets')->andReturn([[ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ], [ 'text' => $faker->paragraph ]]); // When $latestTweets = new LatestTweets($twitterMock); // Then $this->assertCount(5, $latestTweets->tweets()); }}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners