A
A
asdasdqwe2022-01-21 08:03:51
Laravel
asdasdqwe, 2022-01-21 08:03:51

How to create a mock in laravel unit tests?

There is a common unit test

<?php

namespace Tests\Unit\Listeners;

use App\Events\ApplicationSubmittedEvent;
use App\Listeners\NotifyEmployerListener;
use Mockery\MockInterface;
use PHPUnit\Framework\TestCase;

class NotifyEmployerListenerTest extends TestCase
{
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function test_handle()
    {
        $listener = new NotifyEmployerListener();

        $eventMock = $this->mock(ApplicationSubmittedEvent::class, function (MockInterface $mock) {
            $mock->employer = 'test evployer';

            $mock->shouldReceive('notify')->once();
        });

        $listener->handle($eventMock);
    }
}


If you call $this->mock in unit tests, we get the error Call to undefined method Tests\Unit\Listeners\NotifyEmployerListenerTest::mock()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2022-01-21
@asdasdqwe

You are deriving your test class from PHPUnit and are surprised it doesn't have Laravel methods.
PS

I wanted to test the listener separately with a unit test (check that the handle method is called and no one deleted it)
Here it is reasonable to make three tests:
  1. That in your code the right event is generated in the right place. Only the generation is checked, we do not look at whether someone is listening to this event or not.
  2. That your EventServiceProvider is set up so that the right listener is specified for that event. Here we do not look at whether this event is generated somewhere and whether the listener is working.
  3. That your listener works correctly by receiving the event. Here you simply manually call its handle method, passing an event there (as a rule, event classes are simple and there is no point in mocking them, it’s easier to create normally, but there are exceptions) and check its business logic.

This approach assumes that you trust the framework and do not test the logic of its work. It can theoretically misfire or you can break something (for example, turn off the EventServiceProvider), but the likelihood of such a development of events is very small, but this approach greatly simplifies writing tests.
PPS If you have a notify method in an event, then you are doing something wrong. Events are DTOs and should not contain any business logic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question