我尝试对HTTP状态代码进行功能测试,并且我的所有请求都返回404.我正在使用symfony2和api rest,这里是代码:
class UserControllerTest extends WebTestCase
{
public function testdeleteAction()
{
$client = $this->createClient();
// $client = static::createClient();
$crawler = $client->request('DELETE','/user',array(),array(),array('CONTENT_TYPE' => 'application/json'),array());
$response = $client->getResponse();
// print_r($response);
// exit();
// $this->assertTrue($response->isSuccessful());
$this->assertSame(Response::HTTP_CREATED, $response->getStatusCode());
}
public function testpeopleAroundAction()
{
$tab = array(
"images" => array(
"smallImage"=>array(
"w"=>"130",
"h"=>"100",
"density"=>"2"
),
"bigImages"=>array(
"w"=>"1400",
"h"=>"700",
"density"=>"2"
)
)
);
$tab = json_encode($tab);
$client = static::createClient();
$crawler = $client->request('POST', '/users/around',array(),array(),array('CONTENT_TYPE' => 'application/json'),$tab);
$response = $client->getResponse();
$this->assertSame(Response::HTTP_CREATED, $response->getStatusCode());
}
}
这是我的捆绑包中的路由代码:
bla_api_delete_account:
pattern: /user.{_format}
defaults: { _controller: BLAApiBundle:User:delete, _format: ~ }
requirements:
_method: DELETE
bla_api_get_users_around:
pattern: /users/around.{_format}
defaults: { _controller: BLAApiBundle:User:peopleAround, _format: ~ }
requirements:
_method: Post
当我运行命令
时phpunit -c app
我得到:
1) BLA\ApiBundle\Tests\Controller\UserControllerTest::testdeleteAction
Failed asserting that 404 is identical to 201.
2) BLA\ApiBundle\Tests\Controller\UserControllerTest::testpeopleAroundAction
Failed asserting that 404 is identical to 201.
请帮助
答案 0 :(得分:0)
我猜你必须在路线的末尾使用斜线。
使用:
$crawler = $client->request('DELETE','/user/',array(),array(),array('CONTENT_TYPE' => 'application/json'),array());
而不是
$crawler = $client->request('DELETE','/user',array(),array(),array('CONTENT_TYPE' => 'application/json'),array());
顺便说一句,在设置中调用路由器组件然后加载路由是一个好习惯。例如:
class UserControllerTest extends WebTestCase
{
protected $router;
public function setUp()
{
$this->router = static::$kernel->getContainer()->get('router');
}
public function testdelete()
{
$crawler = $client->request('DELETE', $this->router->generate('bla_api_delete_account', array('format' => 'json')));
}
}