【问题标题】:Testing forms in symfony 2 phpunit在 symfony 2 phpunit 中测试表单
【发布时间】:2015-01-31 06:03:36
【问题描述】:

我有一个包含两个字段的表单。提交后,会重定向到显示该表单的同一控制器。

方法如下:

public function chartsAction($path, Request $request)
{
   // display form

   if(isset($_POST))
   {
      // handle form submission
   }
}

当不是 POST 请求时,URL 为charts/

当它是一个 POST 请求时,URL 是例如 charts/dateFrom/2013-08/dateTo/2014-02,所以这是方法的 $path 参数,以及取决于表单的两个变量。


现在我想测试一下。问题是表单重定向给了我相同的图表/网站。它只是不向路由添加 $path 参数。这是怎么回事?我的测试方法:

   public function testChartsAction()
    {
        $crawler = $this->client->request('GET', '/charts', [], [], $this->credintials);

        $form = $crawler->selectButton('dateChooser[Choose]')->form([
            'dateChooser[dateFrom]' => '2014-08',
            'dateChooser[dateTo]'   => '2014-12',
        ]);
        $this->client->submit($form);
        $crawler = $this->client->followRedirect();

        $this->assertTrue($this->client->getResponse()->isRedirect('/charts/dateFrom/2014-08/dateTo/2014-12'));
        $this->assertTrue($this->client->getResponse()->isSuccessful());
    }

第一个断言给了我错误。

【问题讨论】:

  • 在 followRedirect 方法之前尝试测试 isRedirect
  • 它仍然给我 /charts 重定向,没有来自表单的 GET 参数。

标签: php forms unit-testing symfony


【解决方案1】:

我认为您应该跳过“isRedirect”断言。在表单处理程序中,您可以设置一个成功的闪烁消息,该消息将呈现在响应页面中:

$client = $this->makeClient(true);
$client->followRedirects();
$crawler = $client->request('GET', $url);

$form = $crawler->filter('#formID')->form();
$form->setValues(array(
    "formsample[firstname]" => "test firstname",
    "formsample[lastname]"  => "test lastname"
));

$client->setServerParameter("HTTP_X-Requested-With" , "XMLHttpRequest");
$client->submit($form);
$response = $client->getResponse();
$this->assertContains('Your data has been saved!', $response->getContent());

【讨论】:

    猜你喜欢
    • 2015-04-26
    • 1970-01-01
    • 2020-08-09
    • 2019-11-22
    • 1970-01-01
    • 2010-09-13
    • 2018-03-18
    • 2015-01-14
    • 1970-01-01
    相关资源
    最近更新 更多