Bird
Raised Fist0
Laravelframework~20 mins

Mocking and faking in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Laravel Mocking & Faking Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel test using a fake?
Consider this Laravel test code that fakes the mail sending. What will be the result of the assertion?
Laravel
<?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);
    }
}
AThe test fails because Mail::fake() disables sending mails and no mail is sent.
BThe test passes because the mail was sent and caught by the fake.
CThe test throws an error because Mail::assertSent() cannot be used after Mail::fake().
DThe test passes but Mail::assertSent() always returns true regardless of mails sent.
Attempts:
2 left
💡 Hint
Think about what Mail::fake() does and how assertSent works with it.
❓ state_output
intermediate
2:00remaining
What is the value of the mocked method call count?
Given this Laravel test using a mock, what is the value of $count after the calls?
Laravel
<?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;
    }
}
A0
B1
CThrows an error because mockery_getExpectationCount() is not a method
D2
Attempts:
2 left
💡 Hint
Check if mockery_getExpectationCount() is a valid method on the mock object.
🔧 Debug
advanced
2:00remaining
Why does this Laravel test fail when mocking a repository?
This test tries to mock a repository method but fails with a method not found error. Why?
Laravel
<?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);
    }
}
AThe test passes without errors and returns 'User1' as expected.
BThe test fails because the find method does not exist on UserRepository, so Mockery cannot mock it.
CThe test fails because Mockery requires calling Mockery::close() after the test to avoid errors.
DThe test fails because UserRepository is a concrete class and Mockery cannot mock concrete classes by default.
Attempts:
2 left
💡 Hint
Check if the method being mocked exists and if Mockery supports mocking this class.
📝 Syntax
advanced
2:00remaining
Which option correctly fakes the event dispatch in Laravel?
You want to fake event dispatching in a Laravel test. Which code snippet is correct?
A
Event::fake();
Event::assertDispatched(UserRegistered::class);
B
Event::fake(UserRegistered::class);
Event::assertDispatched(UserRegistered::class);
C
Event::fake();
Event::assertDispatched('UserRegistered');
D
Event::fake();
Event::assertDispatched('App\Events\UserRegistered');
Attempts:
2 left
💡 Hint
Check the correct usage of Event::fake() and assertDispatched with class names.
🧠 Conceptual
expert
3:00remaining
What is the main difference between mocking and faking in Laravel testing?
Choose the best explanation of how mocking and faking differ in Laravel testing.
AMocking disables all functionality of a class, while faking allows the original methods to run but logs calls.
BMocking is only used for database queries, while faking is used for HTTP requests and events.
CMocking and faking are the same in Laravel; both replace real implementations with test doubles.
DMocking replaces a class or method with a dummy that records calls and can return custom values, while faking replaces a whole service with a simplified version that simulates behavior without side effects.
Attempts:
2 left
💡 Hint
Think about the scope and purpose of mocks versus fakes in tests.

Practice

(1/5)
1. What is the main purpose of mocking and faking in Laravel testing?
easy
A. To automatically generate user interfaces
B. To simulate external services without performing real actions
C. To permanently store test data in the database
D. To speed up the application in production

Solution

  1. Step 1: Understand mocking and faking concept

    Mocking and faking are used to imitate external services or actions during tests without actually performing them.
  2. Step 2: Identify the purpose in Laravel testing

    Laravel uses mocking and faking to avoid real side effects like sending emails or making HTTP requests during tests.
  3. Final Answer:

    To simulate external services without performing real actions -> Option B
  4. Quick Check:

    Mocking = simulate services [OK]
Hint: Mocking means faking external actions in tests [OK]
Common Mistakes:
  • Thinking mocking speeds up production
  • Confusing mocking with real data storage
  • Assuming mocking creates UI automatically
2. Which Laravel method correctly fakes sending emails in a test?
easy
A. Mail::fake();
B. Mail::sendFake();
C. Mail::mock();
D. Mail::simulate();

Solution

  1. Step 1: Recall Laravel's mail faking method

    Laravel provides the Mail::fake() method to fake email sending during tests.
  2. Step 2: Check method correctness

    Only Mail::fake() is the correct and existing method; others are invalid or do not exist.
  3. Final Answer:

    Mail::fake(); -> Option A
  4. Quick Check:

    Mail::fake() = correct syntax [OK]
Hint: Use Mail::fake() to fake emails in Laravel tests [OK]
Common Mistakes:
  • Using non-existent methods like Mail::sendFake()
  • Confusing mock() with fake()
  • Forgetting the parentheses ()
3. What will the following Laravel test code output?
use Illuminate\Support\Facades\Http;

Http::fake();

$response = Http::get('https://example.com/api');

return $response->status();
medium
A. null
B. 404
C. 500
D. 200

Solution

  1. Step 1: Understand Http::fake() behavior

    Http::fake() fakes all HTTP requests and returns a default successful response with status 200.
  2. Step 2: Analyze the returned status code

    The $response->status() returns 200 because the fake response simulates success.
  3. Final Answer:

    200 -> Option D
  4. Quick Check:

    Http::fake() returns 200 status [OK]
Hint: Http::fake() returns 200 status by default [OK]
Common Mistakes:
  • Assuming fake returns 404 or error
  • Expecting null instead of response object
  • Confusing Http::fake() with real HTTP call
4. Identify the error in this Laravel test code snippet:
use Illuminate\Support\Facades\Storage;

Storage::fake('local');

Storage::put('file.txt', 'Hello');

$this->assertTrue(Storage::exists('file.txt'));
medium
A. Storage::fake() must be called with 'public' disk, not 'local'
B. Storage::exists() should be Storage::disk('local')->exists()
C. No error, the code is correct
D. Storage::put() cannot be used after Storage::fake()

Solution

  1. Step 1: Understand Storage::fake() usage

    Storage::fake('local') fakes the 'local' disk, which is Laravel's default disk.
  2. Step 2: Check method calls for disk specification

    Storage::put() and Storage::exists() use the default disk ('local'), so they interact with the faked disk correctly. The assertion passes.
  3. Final Answer:

    No error, the code is correct -> Option C
  4. Quick Check:

    Default disk = 'local' [OK]
Hint: Storage:: methods use default disk after Storage::fake('local') [OK]
Common Mistakes:
  • Thinking disk must always be explicitly specified
  • Believing Storage::put() is disallowed after fake
  • Confusing required disk names
5. You want to test that your Laravel app sends exactly one notification to a user without actually sending it. Which approach correctly achieves this?
hard
A. Use Notification::fake() and then assertNotificationSent()
B. Use Notification::send() and check the database for records
C. Use Notification::mock() and assertNothingSent()
D. Use Notification::fake() and then assertNothingSent()

Solution

  1. Step 1: Choose the correct faking method for notifications

    Notification::fake() prevents real notifications from sending and allows assertions.
  2. Step 2: Use the right assertion to check one notification sent

    assertNotificationSent() verifies that a notification was sent exactly once to the user.
  3. Final Answer:

    Use Notification::fake() and then assertNotificationSent() -> Option A
  4. Quick Check:

    Notification::fake() + assertNotificationSent() = test notifications [OK]
Hint: Fake notifications, then assertNotificationSent() to check sends [OK]
Common Mistakes:
  • Using assertNothingSent() when expecting a notification
  • Trying to check notifications via database records
  • Using non-existent Notification::mock() method