<?php use Illuminate\Support\Facades\Mail; use Tests\TestCase; class UserTest extends TestCase { public function test_mail_is_sent() { Mail::fake(); Mail::to('user@example.com')->send(new \App\Mail\WelcomeMail()); Mail::assertSent(\App\Mail\WelcomeMail::class); } }
Mail::fake() prevents actual emails from being sent but records the mailables sent. The assertion checks if the mail was sent, so the test passes.
<?php use Illuminate\Support\Facades\Cache; use Tests\TestCase; class CacheTest extends TestCase { public function test_cache_mock() { $mock = \Mockery::mock('alias:Illuminate\Support\Facades\Cache'); $mock->shouldReceive('put')->twice()->andReturn(true); Cache::put('key1', 'value1', 10); Cache::put('key2', 'value2', 10); $count = $mock->mockery_getExpectationCount(); return $count; } }
The method mockery_getExpectationCount() does not exist on the mock object, so calling it causes a fatal error.
<?php use Tests\TestCase; use App\Repositories\UserRepository; use Mockery; class UserRepositoryTest extends TestCase { public function test_find_user() { $mock = Mockery::mock(UserRepository::class); $mock->shouldReceive('find')->with(1)->andReturn('User1'); $result = $mock->find(1); $this->assertEquals('User1', $result); } }
Mockery can mock concrete classes and the find method exists on UserRepository. The test passes and returns the mocked value.
Event::fake() fakes all events. assertDispatched expects the event class name, not a string or partial name.
Mocking creates controlled stand-ins for specific methods or classes to verify interactions. Faking replaces entire services with simplified versions to avoid side effects like sending emails or dispatching events.
