我想测试一个控制器函数getStructuredChartData,它将$chartData作为参数
function getStructuredChartData($chartData = null) {
$structuredChartData = array();
$structuredChartData['Create'] = array();
$structuredChartData['Create']['type'] = 'column';
$structuredChartData['Create']['exportingEnabled'] = TRUE;
if($chartData == null) {
$structuredChartData['null'] = TRUE;
} else {
$structuredChartData['ChartParams'] = array();
$structuredChartData['ChartParams']['renderTo'] = 'columnwrapper';
....
....
....
}
}
为了测试这一点,我在测试用例控制器中编写的代码如下
public function testTrendsReportWithAjaxRequest() {
$chartData = array();
$from_date = new DateTime("2014-07-01");
$to_date = new DateTime("2014-07-31");
$chartData['StartDate'] = $from_date;
$chartData['EndDate'] = $to_date;
$chartData['View'] = "Daily";
$chartData['Data'][(int) 0]['Project']['name'] = 'Test Project #1';
$chartData['Data'][(int) 0][(int) 0] = array('reviewed' => '1', 'modified' => '2014-07-16');
debug($chartData);
// Invoke the index action.
$result = $this->testAction(
'/reports/getStructuredChartData',
array('data' => $chartData)
);
debug($result);
$this->assertNotEmpty($result);
}
现在我关心的是如何将$chartData传递给testCase中的控制器函数。
当前在控制器函数$chartData中出现为NULL和if条件
if($chartData == null) {
$structuredChartData['null'] = TRUE;
}
被执行。此外,我想其他条件
else {
$structuredChartData['ChartParams'] = array();
$structuredChartData['ChartParams']['renderTo'] = 'columnwrapper';
....
....
....
}
要执行。
来自CakePHP测试文档
通过提供数据密钥,向控制器发出的请求将是POST。默认情况下,所有请求都是POST请求。您可以通过设置方法密钥来模拟GET请求:
您必须添加get-as方法:
$result = $this->testAction(
'/reports/getStructuredChartData',
array('data' => $chartData, 'method' => 'get')
);
如果你的路线配置正确,你可以通过完整的网址:
$result = $this->testAction(
'/reports/getStructuredChartData/test'
);
再次从CakePHP文档
// routes.php
Router::connect(
'/reports/getStructuredData/:chartData',
array('controller' => 'reports', 'action' => 'getStructuredData'),
array(
'pass' => array('chartData'),
)
);
要在TestCaseController中传递$chartData作为参数,我所做的是::
$this->controller = new ReportsController();
$result = $this->controller->getStructuredChartData($chartData);