2

Swtiching a over to cakephp 2.1 and just starting to learn unit testing...

When I ArticlesControllerTestCase::testView()

and run

$this->testAction('articles/view/1'); 
debug($this->view); 
debug($this->contents); 
die;

both $this->view and $this->contents is equal to null

I've emptied the beforeFilter calls and beforeRender calls to try and elimitate that...

I noticed that in the controller action, if I set $this->render('view'); at the end of the method I get $this->view = 'what it is suppose to be', but $this->contents = 'to the same thing and does not contain the layout

any idea why this would be happening?

class ArticlesController extends MastersController {

    /*
     * Name
     */
    public $name = 'Articles';

    /*
     * Publicly Accessible Methods
     */
    public $allowed = array('view', 'index', 'category', 'news');


    /*
     * Default Search Params
     */
    public $presetVars = array(
        array('field' => 'title', 'type' => 'value'),
        array('field' => 'category_id', 'type' => 'value'),
        array('field' => 'status_id', 'type' => 'value'),           
    );

    /*
     * Admin Menu Options
     */
    public $adminMenu = array('index'=>array('Category'));

    /**
     * Before Filter Callback
     * (non-PHPdoc)
     * @see controllers/MastersController::beforeFilter()
     * @return void
     */
    public function beforeFilter(){
        parent::beforeFilter();
        $categories = $this->Article->Category->find('class', array('article', 'conditions'=>array('not'=>array('Category.name'=>'Content'))));
        $this->set(compact('categories'));
    }

    /**
     * View
     * @param $id
     * @see controllers/MastersController::_view()
     * @return void
     */
    public function view($id){
        parent::_view($id);
        $articleTitle = $this->Article->findField($id,'title');
        $recentNews = $this->Article->find('recentNews');
        $this->set('title_for_layout', $articleTitle);
        $this->set(compact('recentNews'));
    }
};

class MastersController extends AppController {

    /*
     * Name
     */
    public $name = 'Masters'; # expected to be overridden

    /**
     * View
     * Default view method for all controllers
     * Provides an individual record based on the record id
     * @param int $id: model id
     * @return void
     */
    protected function _view($id){
        $this->Redirect->idEmpty($id, array('action'=>'index'));
        ${Inflector::singularize($this->request->params['controller'])} = $this->{$this->modelClass}->find('record', array($id));
        ${Inflector::variable(Inflector::singularize($this->request->params['controller']))} = ${Inflector::singularize($this->request->params['controller'])};

        if(empty(${Inflector::singularize($this->request->params['controller'])})){
            return $this->Redirect->flashWarning('Invalid Id.', $this->referer());
        }       
        $this->set(compact(Inflector::singularize($this->request->params['controller']), Inflector::variable(Inflector::singularize($this->request->params['controller']))));
    }
}


class ArticlesControllerTestCase extends ControllerTestCase {

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = array('app.article');

    /**
     * Set Up
     *
     * @return void
     */
    public function setUp() {
        parent::setUp();
        $this->Articles = new TestArticlesController();
        $this->Articles->constructClasses();
    }

    /**
     * Tear Down
     *
     * @return void
     */
    public function tearDown() {
        unset($this->Articles);

        parent::tearDown();
    }

    /**
     * Test View
     *
     * @return void
     */
    public function testView() {
        $this->testAction('articles/view/1');
        debug($this->view); die;
    }
}


class ArticleFixture extends CakeTestFixture {

    /**
     * Fields
     *
     * @var array
     */
    public $fields = array(
        'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
        'slug' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 120, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
        'title' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
        'body' => array('type' => 'text', 'null' => false, 'default' => NULL, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
        'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
        'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
        'status_id' => array('type' => 'integer', 'null' => false, 'default' => NULL),
        'category_id' => array('type' => 'integer', 'null' => false, 'default' => NULL),
        'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
        'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_general_ci', 'engine' => 'InnoDB')
    );

    /**
     * Records
     *
     * @var array
     */
    public $records = array(
        array(
            'id' => '1',
            'slug' => NULL,
            'title' => 'Test Article #1 without slug - published',
            'body' => '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>',
            'created' => '2011-02-15 21:14:03',
            'modified' => '2011-02-15 21:14:03',
            'status_id' => '1',
            'category_id' => '5'
        ),
         );
}
4

4 回答 4

1

如果您被重定向,例如,如果会话数据不符合预期,某些身份验证代码会重定向到登录页面,则可能会发生这种情况。如果您没有在测试中设置所需的环境,您将被重定向。您可以通过检查以下值来检查$this->headers

debug("Headers: " . print_r($this->headers));

如果您将其放入测试中并看到类似的array('Location' => 'your_login_page')内容,请确保您的测试环境包含使您的身份验证系统(或任何其他可能插入重定向)满意所需的一切。

于 2016-02-17T00:22:37.320 回答
0

您需要捕获 $this->testAction 的结果并指定要返回的内容(http://book.cakephp.org/2.0/en/development/testing.html#testing-controllers

例如

$result = $this->testAction('articles/view/1', array('return'=>'content'));

debug($result);
于 2012-05-25T15:51:01.853 回答
0

如果您计划执行单元测试,您应该真正考虑测试每个单独的单元。话虽这么说,PHPUnit 在集成到 CakePHP 时相当健壮,可以提供您需要的东西,例如数据和方法模拟。

当我编写单元测试时,它看起来有点像这样:

function testSomeTestCaseWithDescriptiveMethodName(){
    $this->testAction("controller/action/arguments");
    $this->assertEqual([some value or data set], $this->vars["key"];
}

这将允许您在不进行集成测试(包括视图、数据库访问等)的情况下针对创建的值进行测试。

我希望这有帮助。:)

于 2013-08-13T05:44:49.470 回答
-1

我想我知道导致问题的原因。您需要为 testAction() 提供方法。

$this->testAction('articles/view/1', array('method'=>'get')); 
debug($this->view); //should output the view
debug($this->contents);  //should output the contents

恕我直言,文档(http://book.cakephp.org/2.0/en/development/testing.html#testing-controllers)看起来默认是 GET。默认值实际上是 POST - 因此“发布”到文章/视图/1 将一无所获。

于 2012-06-18T01:49:44.203 回答