我有一个控制器,我想为它做一个功能测试。
控制器:
<?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]请求。信息:匹配路线"merchant-report"。{" route_parameters ":{"_controller":"Zanox ' AppBundle '控制器' ReportController:: showAction"、"id":"{id}","_route":"merchant-report"},"request_uri":"http://localhost/merchant/{id}/报告吗?id = 1 "} []
让您知道['id' => 1]在数据库中存在。
第一个问题:为什么失败?
第二个问题:我做功能测试的方式是否正确?
如果您查看日志,您会看到{id}
参数没有被正确替换,而是被添加到Uri的查询字符串中。所以试试输入:
$crawler = $client->request('GET', sprintf('/merchant/%d/report', 1));
当使用GET
时,第三个参数将为URI添加查询参数,当使用POST
时,这些数据将被发布
至于它失败的原因—您可以通过在测试中执行控制器代码时使用调试器来逐步解决问题。对于你的第二个问题,是的,你正在做一个简单的功能测试正确。