测试自定义路由模型绑定
Testing Custom Route Model Binding
我正在尝试测试实现 \Illuminate\Contracts\Routing\UrlRoutable
的自定义 class,但无法调用 resolveRouteBinding
方法。
<?php
namespace Tests\Unit;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class BindingExampleClassTest extends TestCase
{
function test_invoke_resolve_route_binding_method()
{
Route::get('/invoke-route-binding/{binding}', function (BindingExampleClass $binding) {
dd($binding);
});
$this->get('/invoke-route-binding/1');
}
}
class BindingExampleClass implements \Illuminate\Contracts\Routing\UrlRoutable
{
public $id;
public function resolveRouteBinding($value, $field = null)
{
$this->id = $value;
}
public function getRouteKey()
{
// TODO: Implement getRouteKey() method.
}
public function getRouteKeyName()
{
// TODO: Implement getRouteKeyName() method.
}
public function resolveChildRouteBinding($childType, $value, $field)
{
// TODO: Implement resolveChildRouteBinding() method.
}
}
dd
响应为 BindingExampleClass
,id
仍然为空。
在测试函数中注册路由将不包含任何中间件。在 Laravel 中使用路由模型绑定时,必须在路由器实例中定义 \Illuminate\Routing\Middleware\SubstituteBindings::class
中间件。
Route::get('/invoke-route-binding/{binding}', function (BindingExampleClass $binding) {
dd($binding);
})->middleware(\Illuminate\Routing\Middleware\SubstituteBindings::class);
我正在尝试测试实现 \Illuminate\Contracts\Routing\UrlRoutable
的自定义 class,但无法调用 resolveRouteBinding
方法。
<?php
namespace Tests\Unit;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class BindingExampleClassTest extends TestCase
{
function test_invoke_resolve_route_binding_method()
{
Route::get('/invoke-route-binding/{binding}', function (BindingExampleClass $binding) {
dd($binding);
});
$this->get('/invoke-route-binding/1');
}
}
class BindingExampleClass implements \Illuminate\Contracts\Routing\UrlRoutable
{
public $id;
public function resolveRouteBinding($value, $field = null)
{
$this->id = $value;
}
public function getRouteKey()
{
// TODO: Implement getRouteKey() method.
}
public function getRouteKeyName()
{
// TODO: Implement getRouteKeyName() method.
}
public function resolveChildRouteBinding($childType, $value, $field)
{
// TODO: Implement resolveChildRouteBinding() method.
}
}
dd
响应为 BindingExampleClass
,id
仍然为空。
在测试函数中注册路由将不包含任何中间件。在 Laravel 中使用路由模型绑定时,必须在路由器实例中定义 \Illuminate\Routing\Middleware\SubstituteBindings::class
中间件。
Route::get('/invoke-route-binding/{binding}', function (BindingExampleClass $binding) {
dd($binding);
})->middleware(\Illuminate\Routing\Middleware\SubstituteBindings::class);