[英]Why is symfony2 functional test client->request() not getting successful response()?
[英]Symfony2 functional test client request returns error 500
我有一个控制器,我正在尝试对其进行功能测试。
控制器:
<?php
namespace Zanox\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Exception;
/**
*
* @author Mohamed Ragab Dahab <eng.mohamed.dahab@gmail.com>
*
* @Route("merchant")
*
*/
class ReportController extends Controller {
/**
* Show transaction report regarding to the given merchant ID
* @author Mohamed Ragab Dahab <eng.mohamed.dahab@gmail.com>
* @access public
*
* @Route("/{id}/report", name="merchant-report")
*
* @param int $id Merchant ID
*/
public function showAction($id) {
try {
//Order Service
$orderService = $this->get('zanox_app.orderService');
//merchant Orders
$orders = $orderService->getMerchantOrders($id);
//render view and pass orders array
return $this->render('ZanoxAppBundle:Report:show.html.twig', ['orders' => $orders]);
} catch (Exception $e) {
//log errors
}
}
}
我创建了一个功能测试如下:
namespace Zanox\AppBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ReportControllerTest extends WebTestCase {
/**
*
*/
public function testShow() {
//Client instance
$client = static::createClient();
//Act like browsing the merchant listing page, via GET method
$crawler = $client->request('GET', '/merchant/{id}/report', ['id'=> 1]);
//Getting the response of the requested URL
$crawlerResponse = $client->getResponse();
//Assert that Page is loaded ok
$this->assertEquals(200, $crawlerResponse->getStatusCode());
//Assert that the response content contains 'Merchant Listing' text
$this->assertTrue($crawler->filter('html:contains("Merchant Report")')->count() > 0);
}
}
但是,此测试失败,因为第一个断言返回状态 500 而不是 200
测试日志显示:[2015-07-06 21:00:24] request.INFO:匹配路由“merchant-report”。 {"route_parameters":{"_controller":"Zanox\\AppBundle\\Controller\\ReportController::showAction","id":"{id}","_route":"merchant-report"},"request_uri":" http ://localhost/merchant/ {id}/report?id=1"} []
让您知道 ['id' => 1] 存在于 DB 中。
第一个问题:为什么会失败?
第二个问题:我是否以正确的方式进行功能测试?
如果您查看日志,您会发现{id}
参数没有被正确替换,而是添加到您的 Uri 的查询字符串中。 所以尝试:
$crawler = $client->request('GET', sprintf('/merchant/%d/report', 1));
使用GET
,第三个参数将为 URI 添加查询参数,使用POST
,将发布这些数据。
至于它失败的原因 - 您可以通过在测试中执行控制器代码时使用调试器单步执行控制器代码来解决问题。 对于您的第二个问题,是的,您正在正确地进行简单的功能测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.