Jitender Thakur
Jitender Thakur

Reputation: 590

Unable to mock any custom class method in laravel 6

I have a Basic Class Helper.

namespace App\Helpers;

class CommonUtility {

    public static function foo() {
        return 'foo';
    }
}

And it's used in User.php

<?php
class User extends Authenticatable
    public function test() {
        return CommonUtility::foo();
    }
}

And now I wanted to write a test with mocking CommonUtility class. Can anyone know about this I'm new to laravel unit test.

Tried few solutions like

$mock = Mockery::mock(CommonUtility::class, function ($mock) {
            $mock->shouldReceive('foo')->andReturn('foobar');
        })->makePartial();

dd($mock->foo());

it gives me the mock result but i tried it from

$user = new \App\User();
dd($user->test());

It's calling the actual function instead of mock one.

Upvotes: 1

Views: 1365

Answers (1)

Matteo
Matteo

Reputation: 39370

You could use the Aliasing Mockery features for Mocking Public Static Methods

As example:

        $mock = \Mockery::mock('alias:App\Helpers\CommonUtility');
        $mock->shouldReceive('foo')
            ->andReturn('foobar');
        
        $user = new User();
        $this->assertEquals("foobar", $user->test());

The test pass as expected

Upvotes: 2

Related Questions