Table of Contents
2. Using Laravel’s Built-in Facade Fakes and Mocks
Example: Fake the Mail Facade
3. Mocking a Service Bound in the Container
4. Using Http::fake() for External HTTP Calls
5. Partial Mocks – Mock Only Specific Methods
6. Clean Up Mocks After Tests
Key Tips
Home PHP Framework Laravel How to mock objects in Laravel tests?

How to mock objects in Laravel tests?

Jul 27, 2025 am 03:13 AM
laravel unit test

Use Mockery for custom dependencies by setting expectations with shouldReceive(). 2. Use Laravel’s fake() method for facades like Mail, Queue, and Http to prevent real interactions. 3. Replace container-bound services with $this->mock() for cleaner syntax. 4. Use Http::fake() with URL patterns to simulate external API responses. 5. Apply partial mocks with makePartial() to mock only specific methods. 6. Clean up mocks with Mockery::close(), though Laravel’s base test class typically handles this. Prefer fakes for Laravel components and mocks for custom services to ensure tests remain fast, reliable, and isolated.

How to mock objects in Laravel tests?

Mocking objects in Laravel tests is a common practice to isolate your code and avoid side effects—like database calls, external API requests, or queued jobs. Laravel provides several ways to mock objects, thanks to its integration with PHPUnit and the powerful Mockery library.

How to mock objects in Laravel tests?

Here’s how to effectively mock objects in Laravel tests:


1. Using Mockery for Mocking Dependencies

Laravel includes Mockery by default, so you can easily create mocks of classes or interfaces.

How to mock objects in Laravel tests?
use Mockery;
use Illuminate\Support\Facades\Http;

public function test_external_api_is_called()
{
    $mock = Mockery::mock('App\Services\PaymentGateway');
    $mock->shouldReceive('charge')->once()->andReturn(true);

    $this->instance(PaymentGateway::class, $mock);

    // Now run your test logic
    $response = $this->post('/pay');
    $response->assertOk();
}

? The shouldReceive() method sets expectations on how the mock should be used.


2. Using Laravel’s Built-in Facade Fakes and Mocks

For Laravel facades (like Mail, Queue, Cache, Http, etc.), use fake() or spy().

How to mock objects in Laravel tests?

Example: Fake the Mail Facade

use Illuminate\Support\Facades\Mail;

public function test_user_registration_sends_email()
{
    Mail::fake();

    // Perform action
    $this->post('/register', [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'password' => 'secret'
    ]);

    // Assert message was sent
    Mail::assertSent(WelcomeEmail::class, function ($mail) {
        return $mail->hasTo('john@example.com');
    });
}
  • Use Mail::fake() to prevent real emails from being sent.
  • Use assertSent() or assertNotSent() to verify behavior.

✅ Same pattern works for: Queue::fake(), Cache::fake(), Notification::fake(), Http::fake().


3. Mocking a Service Bound in the Container

If you’re using dependency injection and want to replace a service in the container:

$this->instance(SomeService::class, Mockery::mock(SomeService::class, function ($mock) {
    $mock->shouldReceive('process')->once()->andReturn('mocked result');
}));

Or more cleanly:

$this->mock(SomeService::class, function ($mock) {
    $mock->shouldReceive('process')->andReturn('mocked result');
});

? ->mock() is a Laravel helper method that combines Mockery::mock() and app()->instance().


4. Using Http::fake() for External HTTP Calls

Avoid calling real APIs during testing:

Http::fake([
    'api.github.com/*' => Http::response(['name' => 'Laravel'], 200),
]);

// Now make the actual call
$response = Http::get('https://api.github.com/orgs/laravel');

// Assert request was sent
Http::assertSent(function ($request) {
    return $request->url() === 'https://api.github.com/orgs/laravel';
});

You can also use Http::fake()->preventStrayRequests() to ensure only expected URLs are hit.


5. Partial Mocks – Mock Only Specific Methods

Sometimes you want to mock just one method of a class and keep others real.

$service = Mockery::mock(MyService::class)
    ->makePartial()
    ->shouldReceive('externalCall')
    ->andReturn('dummy')
    ->getMock();

$this->instance(MyService::class, $service);

Now only externalCall() is mocked; other methods run normally.


6. Clean Up Mocks After Tests

Always clean up your mocks to avoid test pollution:

protected function tearDown(): void
{
    Mockery::close();
    parent::tearDown();
}

✅ Laravel’s base test classes (like TestCase) usually handle this already.


Key Tips

  • Prefer fakes (Mail::fake(), Queue::fake()) over full mocks when available—they’re simpler and Laravel-specific.
  • Use mocks when you need fine-grained control over return values or behavior.
  • Avoid over-mocking—only mock what you need to isolate.
  • Use spy() to observe actual calls without interfering:
    $this->spy(SomeService::class);
    // Later:
    $this->shouldHaveReceived(SomeService::class, 'method');

    Basically, Laravel makes mocking clean and expressive. Use fakes for Laravel components, and Mockery for custom services. It keeps your tests fast, reliable, and independent of external systems.

    The above is the detailed content of How to mock objects in Laravel tests?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1503
276
What is Configuration Caching in Laravel? What is Configuration Caching in Laravel? Jul 27, 2025 am 03:54 AM

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

How to create a helper file in Laravel? How to create a helper file in Laravel? Jul 26, 2025 am 08:58 AM

Createahelpers.phpfileinapp/HelperswithcustomfunctionslikeformatPrice,isActiveRoute,andisAdmin.2.Addthefiletothe"files"sectionofcomposer.jsonunderautoload.3.Runcomposerdump-autoloadtomakethefunctionsgloballyavailable.4.Usethehelperfunctions

How to mock objects in Laravel tests? How to mock objects in Laravel tests? Jul 27, 2025 am 03:13 AM

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp

How to implement a referral system in Laravel? How to implement a referral system in Laravel? Aug 02, 2025 am 06:55 AM

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

How to seed a database in Laravel? How to seed a database in Laravel? Jul 28, 2025 am 04:23 AM

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4

How to run a Laravel project? How to run a Laravel project? Jul 28, 2025 am 04:28 AM

CheckPHP>=8.1,Composer,andwebserver;2.Cloneorcreateprojectandruncomposerinstall;3.Copy.env.exampleto.envandrunphpartisankey:generate;4.Setdatabasecredentialsin.envandrunphpartisanmigrate--seed;5.Startserverwithphpartisanserve;6.Optionallyrunnpmins

How to build a REST API with Laravel? How to build a REST API with Laravel? Jul 30, 2025 am 03:41 AM

Create a new Laravel project and start the service; 2. Generate the model, migration and controller and run the migration; 3. Define the RESTful route in routes/api.php; 4. Implement the addition, deletion, modification and query method in PostController and return the JSON response; 5. Use Postman or curl to test the API function; 6. Optionally add API authentication through Sanctum; finally obtain a clear structure, complete and extensible LaravelRESTAPI, suitable for practical applications.

Using Events and Listeners in Laravel. Using Events and Listeners in Laravel. Jul 26, 2025 am 08:21 AM

Using events and listeners in Laravel is an effective way to decouple main logic. 1. Create events and listeners can be generated and bound to EventServiceProvider through the Artisan command or enable the automatic discovery mechanism. 2. In actual use, it is necessary to note that an event can correspond to multiple listeners, queue failure retry policy, keep the listener lightweight, and register event subscribers. 3. During testing and debugging, you should confirm the event triggering, listener binding, and queue drive status, and set QUEUE_CONNECTION=sync to perform synchronously to facilitate troubleshooting. 4. Advanced tips include dynamically controlling the execution or registration of the listener according to conditions, but it is recommended to advanced users. Mastering these key points can help improve code control

See all articles