sAnsic's avatar

The method I'm mocking returns a real value

In the test:

        Http::fake();

        $sender = app(Sender::class);

        $mockProvider = \Mockery::mock($sender, function (MockInterface $mock) {
            $mock->shouldReceive('getLimitContactsForRequest')
                ->andReturn(1);
            $mock->makePartial();
        });

        $mockProvider->getLeadContacts(['1', '2']);

        Http::assertSentCount(2);

receive Failed asserting that actual size 1 matches expected size 2

Sender:

    private int $limitContactsForRequest = 50;

    public function getLimitContactsForRequest(): int
    {
        return $this->limitContactsForRequest;
    }

    public function getLeadContacts(array $contactIds = [] ): array
    {
        return collect($contactIds)->chunk($this->getLimitContactsForRequest())
            ->each(fn($contacts) => Http::post('/contacts', $contacts));
    }

What was my mistake?

0 likes
3 replies
kevinbui's avatar

I believe we should mock the class, not an instance of it:

$mockProvider = \Mockery::mock(Sender::class, function (MockInterface $mock) {
            $mock->shouldReceive('getLimitContactsForRequest')
                ->andReturn(1);
            $mock->makePartial();
        });
1 like
tisuchi's avatar
tisuchi
Best Answer
Level 70

@kevinbui I would prefer to write this way:

Http::fake();

// Mock the Sender class and its method
$mockSender = \Mockery::mock(Sender::class)->makePartial();
$mockSender->shouldReceive('getLimitContactsForRequest')->andReturn(1);

// Bind the mocked instance to the Laravel container
$this->app->instance(Sender::class, $mockSender);

// Now, when you resolve the Sender class from the container, you'll get the mock
$sender = app(Sender::class);
$sender->getLeadContacts(['1', '2']);

Http::assertSentCount(2);
2 likes

Please or to participate in this conversation.