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

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners