当我使用built-in tools在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
}
}
如何在不破坏原始第一个会话的情况下,在上述请求之间执行另一个会话请求?
答案 0 :(得分:1)
记住第一个会话数据,刷新应用程序会话,发出“另一个会话”请求并将原始会话数据返回给应用程序:
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);
}
}