Remove a middleware in testing

Submitted by moon0326 - 9 years ago

I was looking for a way to remove one of my middlewares in testing. I could not find it, so I wrote a simple function to do it. Put the following function in your 'TestCase.php'

    public function refreshApplication()
    {
        parent::refreshApplication();
        $this->app->resolving(function (Kernel $kernel, $app) {
            $shouldBeRemoved = ['a middleware', 'another middleware'];

            $reflected = new ReflectionClass($kernel);
            $property = $reflected->getProperty('middleware');
            $property->setAccessible(true);

            $middlewares = $property->getValue($kernel);

            foreach ($middlewares as $key => $middleware) {
                if (in_array($middleware, $shouldBeRemoved)) {
                    unset($middlewares[$key]);
                }
            }

            $property->setValue($kernel, $middlewares);
        });
    }