【问题标题】:Laravel middleware is not called in feature test功能测试中未调用 Laravel 中间件
【发布时间】:2020-04-05 19:34:06
【问题描述】:

我有一个新的中间件,可以在浏览器中按预期工作。但是,当我尝试通过功能测试触发中间件时,永远不会调用 handle()

我知道我可以为这个中间件编写一个单元测试,并且应该这样做。但是我的实际功能测试是否应该转移到浏览器测试中?

# Kernel.php

    protected $middlewareGroups = [
        'web' => [
            MyMiddleware::class,
            ...
# MyMiddleware.php

    public function handle($request, Closure $next)
    {
        dd('I can see this in the browser, but not in the Feature test. Doing some 302 magic here.');
# Feature Test
    /**
     * @test
     * @return void
     */
    public function my_new_test(): void
    {
        $this->get('/test')
            ->assertStatus(302)
            ->assertRedirect($vanityDomain->getFallbackRedirectUrl('/non-matching-path'));
    }

【问题讨论】:

    标签: testing laravel-7


    【解决方案1】:

    它对我有用,不知道为什么你的不起作用。 middleware

    class MyMiddleware
    {
        public function handle($request, Closure $next)
        {
            if ('test' === $request->path()) {
                return redirect('/test1');
            }
    
            return $next($request);
        }
    }
    

    feature test

    class ExampleTest extends TestCase
    {
        /**
         * A basic test example.
         */
        public function testBasicTest()
        {
            $this->get('/test')->assertStatus(302)->assertRedirect('test1');
        }
    }
    

    顺便说一句,单元测试和功能测试只是对测试进行分组的一种方式。不管你放在哪里,它们的行为都是一样的。

    【讨论】:

      【解决方案2】:

      在 laravel 8 上,我必须运行 php artisan optimize 才能让它工作。似乎需要以某种方式清除路由缓存。

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 2016-08-04
        • 2013-08-31
        • 1970-01-01
        • 2020-12-18
        • 2018-01-22
        • 1970-01-01
        相关资源
        最近更新 更多