在Symfony 2 PHPUnit中测试表单

3

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

具体方法如下:

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参数,还有根据表单而定的两个变量。


现在我想要测试它。问题是表单重定向只会给我相同的charts/网站,它不会将$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 进行测试。 - Matteo
它仍然给我/图表重定向,没有来自表单的GET参数。 - khernik
1个回答

3

我认为你应该跳过“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());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接