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:

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

David Albrecht On
public function testValidationFail() {
    $VatValidator = $this->getMockBuilder('Cake\Validation\Validator')
    $this->Users->getValidator()->setProvider('vat', $VatValidator);

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