首页 > 解决方案 > 如何在 Laravel 测试中代表另一个会话发出 HTTP 请求?

问题描述

当我在 Laravel 5 中使用内置工具执行 HTTP 测试时,框架会记住从请求到请求的会话数据。

class HttpTest extends TestCase
{
    public function testApplication()
    {
        // Suppose this endpoint creates a session and adds some data to it
        $this->get('/action/fillSession');

        // Suppose this endpoint reads the session data
        $this->get('/action/readSession'); // The session data from the first request is available here
    }
}

如何在不破坏原始第一个会话的情况下在上述请求之间执行另一个会话的请求?

标签: phplaraveltesting

解决方案


记住第一个会话数据,刷新应用程序会话,发出“另一个会话”请求并将原始会话数据返回给应用程序:

class HttpTest extends TestCase
{
    public function testApplication()
    {
        // Suppose this endpoint creates a session and adds some data to it
        $this->get('/action/fillSession');

        $session = $this->app['session']->all();
        $this->flushSession();
        $this->get('/noSessionHere');
        $this->flushSession();
        $this->session($session);

        // Suppose this endpoint reads the session data
        $this->get('/action/readSession'); // The session data from the first request is available here
    }
}

您可以将此算法执行到单独的方法以轻松重用它:

class HttpTest extends TestCase
{
    public function testApplication()
    {
        // Suppose this endpoint creates a session and adds some data to it
        $this->get('/action/fillSession');

        $this->asAnotherSession(function () {
            $this->get('/noSessionHere');
        });

        // Suppose this endpoint reads the session data
        $this->get('/action/readSession'); // The session data from the first request is available here
    }

    protected function asAnotherSession(callable $action)
    {
        $session = $this->app['session']->all();
        $this->flushSession();

        $action();

        $this->flushSession();
        $this->session($session);
    }
}

推荐阅读