如何在Cakephp中模拟验证提供程序

问题描述 投票:0回答:1

我有一个验证器,用于检查增值编号是否正确。为此,它调用外部服务。这个外部调用减慢了测试速度并且不可靠,所以我想嘲笑它,但我不明白我是怎么做到的。

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

这是验证提供者:

<?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;
        }
    }
}
cakephp cakephp-3.0
1个回答
0
投票
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.