Search code examples
laravelunit-testingmockinglaravel-6mockery

Laravel mocking is not executing


I have been trying too mock a service class in my Laravel 6 unit testing, but the call is moving to the real method rather than mocked response. Here is the People class that I am trying to mock -

class People
{ 
    public static function checkCredentials($username, $password) {
        // some code, which is not supposed to execute while unit testing. 
    }
}

The controller responsible to execute this is -

class AuthController extends Controller {
    public function login(Request $request) {
        $auth = People::checkCredentials($request->username, $request->password);
        dd($auth);  // I am expecting mocked response here i.e., ['abc'].
    }
}

Here is my test class -

class LoginTest extends TestCase {
    /** @test */
    public function a_user_can_login() {
         $this->mock(People::class, function ($mock) {
            $mock->shouldReceive('checkCredentials')
                    ->withArgs(['username', 'password'])
                    ->once()
                    ->andReturn(['abc']);
        });
        $this->assertTrue(true);
    }
}

The dump in controller is returning the real response rather than mocked one. I need help to understand what I am doing wrong. Thanks.


Solution

  • In order to mock a service, the service have to be injected as a service container.

    At the moment you're calling a static method of People class without instantiation of the class.

    $auth = People::checkCredentials($request->username, $request->password);

    Try to inject the class as a service container, so Laravel could catch injection and mock it. You could type-hint it as an parameter of your function.

    class AuthController extends Controller {
        public function login(Request $request, $people People) {
            $auth = $people::checkCredentials($request->username, $request->password);
            dd($auth);  // I am expecting mocked response here i.e., ['abc'].
        }
    }
    

    Mocking objects

    Service Container