【问题标题】:Testing Custom Route Model Binding测试自定义路由模型绑定
【发布时间】:2021-05-14 07:19:41
【问题描述】:

我正在尝试测试实现 \Illuminate\Contracts\Routing\UrlRoutable 的自定义类,但无法调用 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 响应为 BindingExampleClassid 仍为空。

【问题讨论】:

    标签: laravel laravel-routing


    【解决方案1】:

    在测试函数中注册路由不会包含任何中间件。在 Laravel 中使用路由模型绑定时,必须在路由器实例中定义 \Illuminate\Routing\Middleware\SubstituteBindings::class 中间件。

    Route::get('/invoke-route-binding/{binding}', function (BindingExampleClass $binding) {
        dd($binding);
    })->middleware(\Illuminate\Routing\Middleware\SubstituteBindings::class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2019-09-05
      • 2019-01-10
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多