【问题标题】:Symfony2: UnitTests for AJAX ControllersSymfony:AJAX 控制器的单元测试
【发布时间】:2014-06-27 02:34:48
【问题描述】:

我将编写一些 Symfony2 UnitTests(派生自 Symfony\Bundle\FrameworkBundle\Test\WebTestCase)来测试 ajax 控制器,类似于 How to get Ajax post request by symfony2 Controller。 我的大问题是将参数放入请求的“请求”包中,而不是放入“参数”包中。与上例类似,控制器中的方法如下所示:

public function ajaxAction(Request $request) 
{
    $data = $request->request->get('data');
}

但如果我对 $request 进行 var_dump,我在 WebTestCase 中提供的参数不会出现在 $request->request 中,而是出现在 $request->parameter强>。假设这是我的 webtestcase 中的代码部分:

....
$client = static::createClient();
$client->request('POST', '/ajax/blahblah', ... ?????);

我已经尝试在 url 中直接提供参数

/ajax/blahblah?data=whocares

我尝试在数组中指定参数

$client->request('POST', '/ajax/blahblah', array('data' => 'fruityloops'));

但没有任何效果。有机会让它运行吗?

提前致谢

亨尼斯

【问题讨论】:

    标签: php ajax symfony phpunit


    【解决方案1】:

    发出请求后,您需要得到响应。试试这个:

    $client = static::createClient();
    $client->request('POST', '/ajax/blahblah', array('data' => 'fruityloops'));
    $response = $client->getResponse();
    $this->assertEquals(200, $response->getStatusCode());
    
    //convert to array
    $data = json_decode($response->getContent(true), true);
    
    var_dump($data);
    $this->assertArrayHasKey('your_key', $data);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-12
      • 2017-06-26
      • 2011-12-01
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      相关资源
      最近更新 更多