【问题标题】:Laravel Testing Request - Service Provider - Middleware IssueLaravel 测试请求 - 服务提供者 - 中间件问题
【发布时间】:2018-05-03 15:01:29
【问题描述】:

我有一个 Laravel 5.5 应用程序,我有一个服务提供者,我用它在请求中放置一些东西->属性以在任何地方访问它(简化):

    namespace App\Providers;

    use App\Models\Domain;
    use Illuminate\Http\Request;
    use Illuminate\Support\ServiceProvider;

    class GlobalVarsServiceProvider extends ServiceProvider
    {
        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {
            //
        }

        /**
         * Bootstrap the application services.
         *
         * @param Request $request
         *
         * @return void
         */
        public function boot(Request $request)
        {
            $domain = .. get domain with language and  some logic and cache because of multiple domains ..
            $request->attributes->add(['domain' => $domain]);
        }
    }

我在服务提供者中执行此操作,因为这样我就可以在其他服务提供者中使用它,比如我的 ViewComposerServiceProvider,在那里我为视图编写一些内容。我可以像这样在任何地方访问 $domain:

$this->domain = $request->attributes->get('domain');

效果很好。但不在测试中。当我想在中间件的单元测试中访问 $domain 时,$request->attributes 是空的(在 UnitTests 中和 DuskTests 中一样)。

看起来测试环境使用了不同的请求生命周期?如果是,测试环境还有什么不同?

我做错了什么?

-- 编辑--

测试示例:

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

【问题讨论】:

  • 你能分享你的测试的sn-p吗?特别是伪造/调用http请求的代码
  • 当您在浏览器中访问该站点时它可以工作,但在 Dusk 中不可用?
  • 吉普,没有任何问题..

标签: laravel laravel-5 laravel-5.5 laravel-dusk


【解决方案1】:

TestCase 使用具有方法call 的特征MakesHttpRequests。当你在测试中使用get 方法时,它只是一个捷径。

在您的测试中,您可以这样使用它:

$this->call('GET', '/url/here', $yourRequestParametersHere);

【讨论】:

  • 嗯,我想这就是我所做的: $response = $this->get('/'); ?
猜你喜欢
  • 2016-10-06
  • 2017-07-06
  • 2020-01-31
  • 2021-11-01
  • 1970-01-01
  • 2013-08-25
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多