Laravel / Laravel Testing and Debugging

Using Mocking and Faking in Tests

This tutorial will introduce you to the concept of mocking and faking in tests. You'll learn how to create mock data for your tests, how to use Laravel's faking features, and how …

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores writing tests and debugging Laravel applications effectively.

Introduction

In this tutorial, we aim to understand the concepts of mocking and faking in tests. Mocking and faking are fundamental concepts in software testing that allow us to isolate the system under test and create a controlled environment.

By the end of this tutorial, you will learn:
- What is mocking and faking
- How to create mock data for your tests
- How to use Laravel's faking features

Prerequisites:
- Basic understanding of PHP and Laravel
- Basic understanding of unit testing

Step-by-Step Guide

Mocking

Mocking is creating objects that simulate the behavior of real objects. We use them when we don't want to invoke production code or when the real object is difficult to incorporate into the unit test.

Using Mockery

In Laravel, we can use a package called Mockery to create our mock objects. Here's an example:

$mock = Mockery::mock('ClassToMock');
$mock->shouldReceive('methodToMock')
    ->once()
    ->andReturn('mocked value');

Faking

Faking is a little bit different. Rather than creating a mock object and defining the behavior of all its methods, we use a real object with the same interface that has been simplified for testing.

Using Laravel's Faking

Laravel provides several helpers to generate fakes. For example, to fake notifications, we can do:

Notification::fake();

// Perform order dispatch...

Notification::assertSentTo(
    $user,
    OrderShipped::class,
    function ($notification, $channels) use ($order) {
        return $notification->order->id === $order->id;
    }
);

Code Examples

Let's see some practical examples.

Mocking Example

// Create a mock object for the User class
$userMock = Mockery::mock('App\User');

// Define the behavior for the getName method
$userMock->shouldReceive('getName')
    ->once()
    ->andReturn('John Doe');

// Use the mock object
echo $userMock->getName(); // Outputs: John Doe

In the example above, we create a mock object for the User class and define that the getName method should return 'John Doe' when it's called.

Faking Example

// Fake the Notification facade
Notification::fake();

$order = factory(Order::class)->create();

// Dispatch an order
dispatch(new ShipOrder($order));

// Assert a notification was sent to the given users...
Notification::assertSentTo(
    $order->user,
    OrderShipped::class,
    function ($notification, $channels) use ($order) {
        // Check that the order that was shipped is the correct one
        return $notification->order->id === $order->id;
    }
);

In this example, we fake the Notification facade, dispatch an order, and then assert that a notification was sent.

Summary

  • Mocking and faking are useful tools in testing to isolate the system under test and create a controlled environment.
  • Laravel provides easy-to-use ways to create mock objects and fakes.

Practice Exercises

  1. Create a mock object for a class with multiple methods. Define the behavior for each method and write assertions to test the behavior.
  2. Use Laravel's faking features to fake a dispatch of an event and write assertions to ensure the correct event was dispatched.
  3. Use a combination of mocking and faking in a test. Write assertions to test the behavior.

Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help