
本文详解 Symfony 功能测试中出现 LogicException: The request was not redirected 的根本原因——控制器未执行 HTTP 重定向,而是直接渲染响应;重点指出错误源于手动调用 Request::createFromGlobals() 导致请求对象与 Symfony 内核请求上下文脱节,并提供正确注入 Request 对象、配合表单提交与重定向的完整实践方案。
本文详解 symfony 功能测试中出现 `logicexception: the request was not redirected` 的根本原因——控制器未执行 http 重定向,而是直接渲染响应;重点指出错误源于手动调用 `request::createfromglobals()` 导致请求对象与 symfony 内核请求上下文脱节,并提供正确注入 `request` 对象、配合表单提交与重定向的完整实践方案。
在 Symfony 功能测试中,$client->followRedirect() 抛出 LogicException: The request was not redirected,并非表单提交失败,而是控制器根本未发起重定向响应。观察你的控制器代码:
public function index(ManagerRegistry $doctrine): Response
{
// ❌ 错误:手动创建 Request 实例,脱离 Symfony 请求生命周期
$request = Request::createFromGlobals();
if ($request->isMethod('post')) {
// ... 处理数据 ...
$confirmation = '<p id="confirmation">Well done</p>';
}
return $this->render('add/index.html.twig', [
'confirmation' => $confirmation,
]);
}
此处存在两个关键问题:
- 未执行重定向:$this->render() 返回的是 200 响应,而 followRedirect() 仅对 3xx 状态码(如 302)生效;
- 手动创建 Request 实例:Request::createFromGlobals() 创建的是独立请求对象,无法被 Symfony 表单组件、CSRF 验证或事件监听器识别,导致 POST 数据虽能读取,但整个请求流程与内核脱钩——这间接掩盖了更深层的设计缺陷。
✅ 正确做法是:移除手动创建 Request,改为依赖注入,并显式执行重定向。
✅ 步骤一:修正控制器 —— 注入 Request 并重定向
#[Route('/add', name: 'app_add')]
public function index(ManagerRegistry $doctrine, Request $request): Response
{
$entityManager = $doctrine->getManager();
$transaction = new Transactions();
if ($request->isMethod('POST')) {
$transaction->setCoin($request->request->get('coin'));
$transaction->setValue((float) $request->request->get('value'));
$transaction->setQuantity((int) $request->request->get('quantity'));
$transaction->setDate(new \DateTime());
$entityManager->persist($transaction);
$entityManager->flush();
// ✅ 关键:使用 redirectToRoute() 发起 302 重定向
return $this->redirectToRoute('app_add_success'); // 或重定向到自身 + 查询参数
}
return $this->render('add/index.html.twig');
}
? 提示:若需显示确认信息,推荐通过 FlashBag 实现(如 $this->addFlash('success', 'Well done!')),并在模板中渲染,而非拼接 HTML 字符串。
✅ 步骤二:更新测试用例 —— 匹配重定向行为
/** @test */
public function addCoin(): void
{
$client = static::createClient();
$crawler = $client->request('GET', '/add');
$this->assertResponseIsSuccessful();
$form = $crawler->selectButton('ADD')->form(); // 注意按钮文本为 "ADD",非 "AJOUTER"
$form['coin']->select('bitcoin');
$form['quantity'] = '1';
$form['value'] = '40000';
$client->submit($form);
// ✅ 现在可安全调用 followRedirect()
$crawler = $client->followRedirect();
// 若重定向至成功页,验证其内容
$this->assertSelectorExists('h1:contains("Success")');
// 或验证 Flash 消息(需在模板中渲染)
$this->assertSelectorTextContains('.flash-success', 'Well done!');
}
⚠️ 注意事项与最佳实践
- 永远避免 Request::createFromGlobals():在控制器中,Symfony 已自动注入当前请求对象,手动创建会破坏依赖注入、CSRF 防护、表单绑定等核心机制;
- 区分「渲染」与「重定向」:followRedirect() 仅适用于 redirect() / redirectToRoute() 等返回 RedirectResponse 的操作;单纯 render() 不触发重定向;
- 表单按钮匹配:确保 selectButton() 中的文本与模板中
- 类型安全处理输入:对 value 和 quantity 使用 (float) / (int) 强制转换,避免数据库类型不匹配;
- 启用 CSRF 保护(推荐):在表单中添加 {{ csrf_token('add_coin') }},并在控制器中校验,提升安全性。
遵循以上重构,你的测试将稳定通过,同时代码也更符合 Symfony 最佳实践——松耦合、可测试、可维护。










