Orchestra Testbench当前路由始终返回null

时间:2018-01-03 10:42:47

标签: php laravel laravel-5 phpunit

当我在Laravel项目中使用它时,我正在使用Laravel软件包,但是当我想用 Orchestra Testbench 测试它时,我总是在middlware中获得当前路由null。 / p>

在Github上测试目录:https://github.com/yoeunes/larafast/tree/master/tests

Base TestCase:

class TestCase extends Orchestra\Testbench\TestCase
{
    protected function getEnvironmentSetUp($app)
    {
        $kernel = app('Illuminate\Contracts\Http\Kernel');

        $kernel->pushMiddleware(\Illuminate\Session\Middleware\StartSession::class);
        $kernel->pushMiddleware(\Yoeunes\Larafast\Middlewares\BlacklistRoutes::class);
    }
}

WebControllerTest:

class WebControllerTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();

        /** @var \Illuminate\Routing\Router $router */
        $router = $this->app['router'];

        $router->resource('lessons', 'Yoeunes\Larafast\Tests\Stubs\Controllers\Web\LessonController');
    }

    /** @test */
    public function it_show_create_page()
    {
        /** @var TestResponse $response */
        $response = $this->call('get', '/lessons/create');
        dd($response);
        $response->assertSuccessful();
        $response->assertSee('<title>lessons create |  Larafast</title>');
        $response->assertSee('<i class="fa fa-plus-circle"></i> lessons create');
        $response->assertSee('<form method="POST" action="http://localhost/lessons" accept-charset="UTF-8" enctype="multipart/form-data">');
    }
}

BlacklistRoutes中间件:

class BlacklistRoutes
{
    public function handle($request, Closure $next)
    {
        dd(app('router')->getCurrentRoute()); // always get null
        if (null !== ($route = app('router')->getCurrentRoute())
            && is_a($controller = $route->getController(), Controller::class)
            && in_array($route->getActionMethod(), $controller->getBlacklist(), true)) {
            throw new BlacklistRouteException();
        }

        return $next($request);
    }
}

1 个答案:

答案 0 :(得分:0)

根据Orchestra Testbench Github存储库:

  

AFAIK全球中间件在路由解决之前解决,   因此getCurrentRoute()不应该可用。

所以解决我的问题我可以从控制器构造函数中访问当前路径,如下所示:

public function __construct() 
{ 
    $this->middleware(function ($request, Closure $next) { 
        if (null !== ($route = app('router')->getCurrentRoute())
            && is_a($controller = $route->getController(), Controller::class)
            && in_array($route->getActionMethod(), $controller->getBlacklist(), true)) {

            throw new BlacklistRouteException();
        }
    }); 
}