2012-12-27 240 views
-1

我的驗證失敗,所以我對此消息的測試每次都拋出ValidationException。 「並非所有字段填寫正確」。爲什麼?模擬地,它適用於用戶(另一種方法)。CakePHP:驗證()失敗

MODEL:

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'); 
    } 
} 

的TestClass:

public function testSaveNewInstitution() { 
    $data = array(
     'Institution' => array(
      'name' => 'Spitex Staufen', 
      'address' => 'Hauptweg 4', 
      'postcode' => '1234', 
      'city' => 'huuh', 
      'phone_number' => '123 456 78 90', 
      'email' => '[email protected]', 
      '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' => '[email protected]', 
      'comment' => '', 
      'is_active' => TRUE, 
      'user_id' => 2, 
      'institution_type_id' => 5 
      )); 

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

和所有Exceptionhandling方法是這樣的:

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

回答

0

我不知道我是否真的知道了 - 是Testclass失敗還是saveNewInstitution()函數讓你煩惱?你有沒有試圖檢查saveNewInstitution()是否正常工作 - 把一些數據放在一個表單中傳遞給你的函數?

也許這只是一件小事,並且您的數據庫中有一個id = 2的條目,您得到了一個由您自己的異常方法testSaveNewInstitutionExceptionName()覆蓋的重複鍵異常。