A
A
Andrey Boychenko2021-05-21 23:33:46
PHPUnit
Andrey Boychenko, 2021-05-21 23:33:46

Fundamental do not understand mocks?

Guys, hello everyone. A question about unit tests, since I dealt with integration tests quite well)
There is a service method that puts a certain number of jobs in a queue. This method takes an interface as an argument.

Method

public function createThumbnails(PartnerSettingRepositoryInterface $partnerSettingRepository)
    {
        $seconds = 2;

        foreach ($this->emailTemplateRepository->getTemplates() as $template) {
            $job = new CreateCustomTemplatesThumbnail($template, $this, $partnerSettingRepository);
            $job->delay(now()->addSeconds($seconds));
            $job->onQueue(config('queue.connects.files'));

            dispatch($job);

            $seconds += 2;
        }
    }


I am writing a test which should check this method.
function it_should_push_create_thumbnails_queue()
    {
        Queue::fake();

        $tmp = factory(EmailTemplate::class)->make();

        $emailTemplateRepository = $this->getMockBuilder(EmailTemplateRepository::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['getTemplates'])
            ->getMock();

        $emailTemplateRepository->expects($this->once())->method('getTemplates')
            ->withAnyParameters()
            ->willReturn(collect($tmp));

        $emailTemplateRepository->getTemplates();

        //До вот этого момента все работает, все что ниже - ломается.

        $service = $this->createMock(EmailThumbnailService::class);
        $service->expects($this->once())->willReturnSelf();

        $partnerSettingRepositoryInterface = $this->getMockBuilder(PartnerSettingRepositoryInterface::class);
        $partnerSettingRepositoryInterface->onlyMethods([])->getMock();
        $service->createThumbnails($partnerSettingRepositoryInterface);

        Queue::assertPushedOn(
            config('queue.connects.files'),
            CreateCustomTemplatesThumbnail::class
        );
    }


I get
TypeError: Argument 1 passed to Mock_EmailThumbnailService_6dcb9b1d::createThumbnails() must implement interface App\Repositories\Settings\PartnerSettingRepositoryInterface, instance of PHPUnit\Framework\MockObject\MockBuilder given, called in /var/project/tests/Unit/Services/Newsletter /EmailThumbnailServiceTest.php on line 138


I'm asking for help, even advice. I'm still having trouble with tests, especially mocks. But I really want to understand how it works. Can you provide a link to a relevant article?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Gordinskiy, 2021-05-22
@DmitriyGordinskiy

The problem should go away if you create mocks in setUp, and already configure them in the tests themselves.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question