我在Laravel中创建了一个自定义验证规则,在服务提供商的register()
方法中扩展它,我想测试它,但不知道如何。
我看了Laravel framework's validation tests,但我无法理解getTranslator()
和getRealTranslator()
方法的目的。
有人可以给我一些关于如何测试Laravel自定义验证规则的提示吗?
修改
这就是我所做的:
按如下方式创建ValidatorServiceProvider
:
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ValidatorServiceProvider extends ServiceProvider {
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->app['validator']->extend('greater_than', function($attr, $val, $params)
{
return false;
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
}
}
还将其添加到providers数组并发布composer dump-autoload -o
。
将以下内容添加到tests\CustomValidationRulesTest.php
:
<?php
use Mockery as m;
use Illuminate\Validation\Validator;
class CustomValidationRulesTest extends TestCase {
public function tearDown()
{
m::close();
}
public function testValidateGreaterThan()
{
$trans = $this->getTranslator();
$rules = [
'field2' => 'greater_than:field1'
];
$data = [
'field1' => 1,
'field2' => 2
];
$v = new Validator($trans, $data, $rules);
$this->assertTrue($v->passes());
}
protected function getTranslator()
{
return m::mock('Symfony\Component\Translation\TranslatorInterface');
}
protected function getRealTranslator()
{
$trans = new Symfony\Component\Translation\Translator('en', new Symfony\Component\Translation\MessageSelector);
$trans->addLoader('array', new Symfony\Component\Translation\Loader\ArrayLoader);
return $trans;
}
}
运行PHPUnit给出了以下内容:
PHPUnit 4.6.6 by Sebastian Bergmann and contributors.
Configuration read from /home/ubuntu/workspace/phpunit.xml
E.
Time: 248 ms, Memory: 14.75Mb
There was 1 error:
1) CustomValidationRulesTest::testValidateGreaterThan
BadMethodCallException: Method [validateGreaterThan] does not exist.
/home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:2615
/home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:372
/home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:372
/home/ubuntu/workspace/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:325
/home/ubuntu/workspace/tests/CustomValidationRulesTest.php:27
我做错了什么?
谢谢!
答案 0 :(得分:3)
您需要了解Container
或IoC
以及Validator
在那里注册的方式。
Laravel将Illuminate\Validation\Factory
的实例注册为validator
。因此,如果您检查\Illuminate\Support\Facades\Validator
,则会发现它已解析为Factory
。扩展验证器时,实际上是在Factory
中添加了扩展名。现在,调用Validator::make()
会调用包含扩展名的Factory
,并创建包含扩展名的Validator
,而实例化新的Illuminate\Validation\Validator
则无法解析来自Factory
的扩展。
您不应该实例化新的Validator
,而是使用app('validator')->make()
。
答案 1 :(得分:1)
接受它:
protected function getRealTranslator()
{
$loader = new \Illuminate\Translation\ArrayLoader;
$translator = new \Illuminate\Translation\Translator($loader, 'ja');
return $translator;
}