【问题标题】:CakePHP: validation( ) failsCakePHP:验证()失败
【发布时间】:2012-12-12 23:27:58
【问题描述】:

我的验证失败,所以我对此消息的测试每次都会抛出一个ValidationException。 “并非所有字段都填写正确”。为什么?类似地,它适用于用户(另一种方法)。

型号:

public $validate = array(
    'name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Name can not be empty',
        ),
        'unique' => array(
            'rule' => 'isUnique',
            'message' => 'This name is already used.',
        ),
    ),
    'address' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Address can not be empty',
        ),

...

public function saveNewInstitution($institutionData, $userId) {
    $institutionData[$this->alias]['is_active'] = 1;
    $institutionData[$this->alias]['user_id'] = $userId;
    $this->create();
    $this->set($institutionData);
    if ($this->validates()) {
        return $this->save();
    } else {
        throw new ValidationException('Not all fields are filled out correct');
    }
}

测试类:

public function testSaveNewInstitution() {
    $data = array(
        'Institution' => array(
            'name' => 'Spitex Staufen',
            'address' => 'Hauptweg 4',
            'postcode' => '1234',
            'city' => 'huuh',
            'phone_number' => '123 456 78 90',
            'email' => 'staufen@spitex.huuh',
            'comment' => '',
            'institution_type_id' => 5
            ));
    $expected = array(
        'Institution' => array(
            'id' => 2,
            'name' => 'Spitex Staufen',
            'address' => 'Hauptweg 4',
            'postcode' => '1234',
            'city' => 'huuh',
            'phone_number' => '123 456 78 90',
            'email' => 'staufen@spitex.huuh',
            'comment' => '',
            'is_active' => TRUE,
            'user_id' => 2,
            'institution_type_id' => 5
            ));

    $result = $this->Institution->saveNewInstitution($data, 2);
    $this->assertEqual($result, $expected);
}

所有的异常处理方法都是这样的:

public function testSaveNewInstitutionExceptionName() {
    $this->setExpectedException('ValidationException');
    $this->Institution->saveNewInstitution($this->__nameEmpty, 2);
}

【问题讨论】:

    标签: validation cakephp phpunit


    【解决方案1】:

    我不知道我是否真的明白了 - 你的 Testclass 是失败了还是 saveNewInstitution() 函数给你带来了麻烦?您是否尝试手动检查 saveNewInstitution() 是否正常工作 - 将一些数据放入表单中并将其传递给您的函数?

    也许这只是一件小事,并且您的数据库中有一个 id=2 的条目,并且您有一个重复的键异常被您自己的异常方法 testSaveNewInstitutionExceptionName() 覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2012-03-15
      • 2012-10-18
      • 2017-09-21
      相关资源
      最近更新 更多