1

单元测试新手...测试文章控制器,但我遇到了失败$this->assertNotEmpty();

这不应该显示一个充满验证错误的数组吗?相反,我得到一个空数组。

似乎我的验证规则没有被采纳......因为进一步的检查表明 Article::save() 在应该失败的数据上返回 true......

/**
     * Admin Add
     * @see controllers/MastersController::_admin_add()
     * @return void
     */
    public function admin_add(){
        //parent::_admin_add();
            if(!empty($this->request->data){
            $this->Article->save($this->request->data);
            }
    }

/**
     * Test Admin Add
     *
     * @return void
     */
    public function testAdminAdd() {
        #define sample passing data     
        $sampleDataPass = array(
            'Article'=>array(
                'title'=>'Test Article Add Will Pass',
                'body'=>'Test Article Add Body',
                'status_id'=>1,
                'category_id'=>1,
            )
        );

        #test action        
        $this->testAction('admin/articles/add', array('data'=>$sampleDataPass));
        $this->assertEmpty($this->Articles->Article->validationErrors); #####PASSES#####

        #define sample failing data     
        $sampleDataFail = array(
            'Article'=>array(
                'title'=>'Test Article Add Will Fail',
            )
        );



        $this->testAction('admin/articles/add', array('data'=>$sampleDataFail));
        $this->assertNotEmpty($this->Articles->Article->validationErrors); #####FAILS#####  
    }

class Article extends AppModel {

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

    /*
     * Validation Rules
     */
    public $validate = array(
        'title' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'You must supply an article title in order to save.',
            ),
        ),
        'body' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'You must supply an article title in order to save.',
            ),
        ),
        'status_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                'message' => 'You must choose a status.',
                'allowEmpty' => false,
            ),
        ),
        'category_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                'message' => 'You must choose a category.',
                'allowEmpty' => false,
            ),
        )
    );
}
4

1 回答 1

2

如果数据中不存在该字段,CakePHP 将忽略验证规则。

通过将选项“必需”设置为 true,将始终检查验证规则。

例如:

   'title' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'You must supply an article title in order to save.',
            'required' => true
        ),
    ),

关于 CakePHP 验证的文档可以在这里找到:http: //book.cakephp.org/2.0/en/models/data-validation.html#one-rule-per-field

于 2012-05-17T21:14:02.700 回答