igoshev / laravel-captcha

Captcha integration for the Laravel
https://laravel.bonecms.tech/laravel-captcha
MIT License
79 stars 35 forks source link

Mocking CAPTCHA #44

Open cosmin84 opened 4 years ago

cosmin84 commented 4 years ago

Hello, Is there any way to mock the CAPTCHA in an unit for feature test? Thanks!

ismaail commented 3 years ago

My solution, forcing the captcha validation rule to just return true:

public function testSomething()
{
    $this->mockValidatorExtension(config('bone.captcha.validator'), function () { return true; });

    //.......
}

/**
 * @param string $rule
 * @param \Closure|string $extensionStub
 */
private function mockValidatorExtension($rule, $extensionStub)
{
    $validator = $this->app->get('validator');

    $reflection = new ReflectionClass($validator);
    $property = $reflection->getProperty('extensions');
    $property->setAccessible(true);

    $extensions = $property->getValue($validator);

    $extensions[$rule] = $extensionStub;

    $property->setValue($validator, $extensions);
}

credits: https://github.com/framgia/laravel-test-guideline/blob/master/en/Unit/Validation.md