Php 如何在Laravel测试中使HTTP请求代表另一个会话?

Php 如何在Laravel测试中使HTTP请求代表另一个会话?,php,laravel,testing,Php,Laravel,Testing,当我使用在Laravel5中执行HTTP测试时,框架会记住每个请求之间的会话数据 class HttpTest extends TestCase { public function testApplication() { // Suppose this endpoint creates a session and adds some data to it $this->get('/action/fillSession');

当我使用在Laravel5中执行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
    }
}

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

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

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);
    }
}