php - 如何在 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
}
}
如何在不破坏原始第一个会话的情况下在上述请求之间执行另一个会话的请求?
解决方案
记住第一个会话数据,刷新应用程序会话,发出“另一个会话”请求并将原始会话数据返回给应用程序:
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);
}
}
推荐阅读
- python - 根据“LastModified”将所有文件从一个 S3 位置移动到另一个(相同的存储桶)
- java - 为什么我在 java 中使用 selenium webdriver 时会出现此错误?
- php - 尝试连接到另一台服务器时达到空闲超时
- .net-core - 如何在 EF Core 中使用 T4 模板生成服务和其他类?
- java - 枚举和编程接口
- ibm-midrange - 禁用 Fn 键 Dspf Rpgle
- typescript - 使用来自对象 B(相同类型)的值更新对象 A(的子集)的最佳方法
- r - 如何重新排序组合ggplot2图中的图?
- rabbitmq - 使用 MassTransit、rabbitmq-message-deduplication 插件和 RabbitMQ 时,发布者确认不起作用
- swift - 有没有办法在没有 2000 if else 语句的情况下在 XCode 中编写这个?