Php 如何在Laravel中模拟验证规则
我想模拟自定义验证规则(例如App\Rules\SomeRule)。但当我运行测试时,它给出了一个应该调用的Php 如何在Laravel中模拟验证规则,php,laravel,mocking,mockery,Php,Laravel,Mocking,Mockery,我想模拟自定义验证规则(例如App\Rules\SomeRule)。但当我运行测试时,它给出了一个应该调用的mockry\Exception\InvalidCountException:Method 正好1次,但调用了0次。 我已经阅读了拉威尔的文档,但我不明白为什么我没有成功地模仿这个规则 我读过,但我很难把它与我的问题联系起来,那就是“我如何测试我的应用程序是否使用了这个规则”。或者这是我无法测试的东西 这是我的规则 namespace-App\Rules; 使用照明\合同\验证\规则; 类
mockry\Exception\InvalidCountException:Method
正好1次,但调用了0次。
我已经阅读了拉威尔的文档,但我不明白为什么我没有成功地模仿这个规则
我读过,但我很难把它与我的问题联系起来,那就是“我如何测试我的应用程序是否使用了这个规则”。或者这是我无法测试的东西
这是我的规则
namespace-App\Rules;
使用照明\合同\验证\规则;
类SomeRule实现规则
{
公共函数传递($attribute,$value)
{
//如果有效,则返回TRUE。
}
公共功能消息()
{
//
}
}
我的控制器
namespace App\Http\Controllers;
use App\Rules\SomeRule;
use Illuminate\Http\Request;
class LoanController extends Controller
{
public function store(Request $request)
{
$request->validate([
'email' => ['required', new SomeRule]
]);
// ...insert in database, return json.
}
}
我的测试
namespace Tests\Feature;
use Mockery;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Rules\SomeRule;
class LoansTest extends TestCase
{
use RefreshDatabase;
public function tearDown(): void
{
parent::tearDown();
Mockery::close();
}
/** @test */
public function the_sad_path__when_email_is_invalid()
{
$rule = Mockery::mock(SomeRule::class)->shouldReceive('passes')->once();
$this->app->instance(SomeRule::class, $rule);
$response = $this->json('POST', '/api/loans', ['email' => 'whatevs@gmail.com']);
}
}
我想在AppServiceProvider中注册一些规则。但这仍然没有起到任何作用:
public function register()
{
$this->app->bind(SomeRule::class, function ($app) {
return new SomeRule();
});
}
您需要像这样使用中的代码
class LoanController extends Controller
{
public function store(Request $request)
{
$request->validate([
'email' => ['required', new SomeRule()]
]);
// ...insert in database, return json.
}
}
你知道两者的区别吗?在中,它没有
()
<代码>'name'=>['required','string',新大写],没关系。你能解决这个问题吗?我正在模拟测试中自定义验证器的passs方法,并抛出“method…”。。。。“不存在”错误检查此项:这是否回答了您的问题?