mockingautomated-testslaravel-8grecaptcha

How can I mock a Class in Laravel 8.0?


I'm trying to test a form that has gRecaptcha:

I added a mock following the Laravel Docs :

$this->mock(GoogleRecaptcha::class, function (MockInterface $mock) {
     $mock->shouldReceive('isValid')->once()->andReturn(true);
});

After that it runs the post request, but as it seems to actually be running the mocked class from the controller, it is throwing an error. I thought that the mock shouldn't run it. Maybe I'm doing something wrong with the mock.

In the controller, after the validation, it runs this code:

if (!(new GoogleRecaptcha)->isValid()) {
    abort(403, 'It seems that you are a robot');
}

The GoogleRecaptcha is just a class in the App\Support folder, with only one method: "isValid".

Thanks anyway. Hernán.


Solution

  • To mock a class using laravel service container you must use dependency injection or service location. In this case, the test failed because the GoogleRecaptch class was instantiated using the reserved word new.

    Change it to:

    app(GoogleRecaptch::class)->isValid()
    

    The service container will resolve it.