简体   繁体   English

Symfony2:AJAX控制器的单元测试

[英]Symfony2: UnitTests for AJAX Controllers

I'm going to write some Symfony2 UnitTests (derived from Symfony\\ Bundle\\ FrameworkBundle\\ Test\\ WebTestCase) to test ajax controllers, similar to this How to get Ajax post request by symfony2 Controller . 我将编写一些Symfony2单元测试(源自Symfony \\ Bundle \\ FrameworkBundle \\ Test \\ WebTestCase)来测试ajax控制器,类似于此如何通过symfony2 Controller获取Ajax发布请求 My big problem is to get the parameters into the "request" bag of the request, not into the "parameter" bag. 我的大问题是将参数放入请求的“请求”包中,而不放入“参数”包中。 Similar to the upper example the method in the controller looks like this: 与上例类似,控制器中的方法如下所示:

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

But if i do a var_dump of the $request, the paramaters i supply in the WebTestCase do not appear in $request-> request , but in $request-> parameter . 但是,如果我执行$ request的var_dump,则我在WebTestCase中提供的参数不会出现在$ request-> request中 ,而是出现在$ request-> parameter中 Let's say this is the portion of code in my webtestcase: 假设这是我的webtestcase中的代码部分:

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

I already tried supplying the parameter(s) directly within the url as 我已经尝试过直接在网址中提供参数,如下所示:

/ajax/blahblah?data=whocares

I tried specifying the parameter within an array 我尝试在数组中指定参数

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

But nothing worked. 但是没有任何效果。 Any chance to get this running? 有机会运行吗?

Thanks in advance 提前致谢

Hennes 亨尼斯

After you make the request, you need to get the response. 发出请求后,您需要获得响应。 Try this: 尝试这个:

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM