将数据作为参数传递给测试用例cakephp中的操作

时间:2014-09-18 12:07:06

标签: php cakephp testing

我想测试一个控制器函数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';
            ....
            ....
            ....
        }
}

并测试这个我在testcase控制器中编写的代码如下

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中的控制器函数。

目前在Controller函数中$ chartData出现为NULL和if条件

        if($chartData == null) {
            $structuredChartData['null'] = TRUE;
        } 

被执行。而且我想要其他条件

        else {
            $structuredChartData['ChartParams'] = array();
            $structuredChartData['ChartParams']['renderTo'] = 'columnwrapper';
            ....
            ....
            ....
        }

要执行。

2 个答案:

答案 0 :(得分:3)

来自CakePHP testing documentation

  

通过提供数据密钥,对控制器的请求将是POST。默认情况下,所有请求都是POST请求。您可以通过设置方法键来模拟GET请求:

您必须添加get as method:

 $result = $this->testAction(
            '/reports/getStructuredChartData',
            array('data' => $chartData, 'method' => 'get')
    );

如果您的路线配置正确,您只需传递完整的网址:

 $result = $this->testAction(
                '/reports/getStructuredChartData/test'
        );

再次来自CakePHP docs

// routes.php
Router::connect(
    '/reports/getStructuredData/:chartData', 
    array('controller' => 'reports', 'action' => 'getStructuredData'),
    array(
        'pass' => array('chartData'),
    )
);

答案 1 :(得分:1)

要在TestCaseController中传递$ chartData作为参数,我所做的是::

        $this->controller = new ReportsController();            
        $result = $this->controller->getStructuredChartData($chartData);