I have a validator that checks if a vat-number is correct. In order to do that it calls an external service. This external call slows the tests down and is unreliable, so I would like to mock it, but I don't understand how I could do it.

public function validationDefault(Validator $validator)
{
    $validator->setProvider('vat', 'App\Model\Validation\VatValidation');
    $validator->add('vat_no', 'isValidVatNo', [
        'rule' => 'validVatNumber',
        'provider' => 'vat',
    ]);
}

And this is the validation provider:

<?php
namespace App\Model\Validation;
use Cake\Core\Configure;
use Cake\Validation\Validation;
use VatNumberCheck\Utility\Model\VatNumberCheck;

class VatValidation extends Validation
{
    public static function validVatNumber($check)
    {
        $vatNumberCheck = new VatNumberCheck();
        try {
            return $vatNumberCheck->check($check);
        } catch (InternalErrorException $e) {
            return false;
        }
    }
}

1 Answers

0
David Albrecht On
public function testValidationFail() {
    $VatValidator = $this->getMockBuilder('Cake\Validation\Validator')
        ->setMethods(['validVatNumber'])
        ->getMock();
    $VatValidator->expects($this->any())
        ->method('validVatNumber')
        ->will($this->returnValue(false));
    $this->Users->getValidator()->setProvider('vat', $VatValidator);

    $user = $this->Users->newEntity([
        'vat_no' => 'asdf',
    ]);
    $errors = $user->errors();
    $this->assertArrayHasKey('vat_no', $errors);
}