2012-04-29 23 views
6

tôi có mô hình uploadform sauYii - Mô hình Unittesting một hình thức upload

class TestUploadForm extends CFormModel 
{ 
public $test; 

public function rules() 
{ 
    return array(
     array(test, 'file', 'types' => 'zip, rar'), 
    ); 
} 

Câu hỏi của tôi là, làm thế nào tôi có thể kiểm tra đơn vị này? Tôi đã thử một số nội dung như:

public $testFile = 'fixtures/files/yii-1.1.0-validator-cheatsheet.pdf'; 

public function testValidators() 
{ 
    $testUpload = new TestUploadForm; 

    $testUpload->test = $this->testFile ; 
    assertTrue($testUpload ->validate()); 

    $errors= $testUpload ->errors; 
    assertEmpty($errors); 
} 

Tuy nhiên, điều đó vẫn cho tôi biết trường chưa được điền đầy đủ.

+0

+1. trường 'tài liệu' là gì? và tại sao bạn chưa đặt trường $ test? –

+0

là trường 'tài liệu' một chuỗi? –

+0

woeps, dán sao chép xấu. test = document. – SnIpY

Trả lời

5

Như chúng ta biết rằng Yii sử dụng CUploadedFile, để tải lên tệp, chúng tôi phải sử dụng nó để khởi tạo thuộc tính tệp của mô hình.

Chúng tôi có thể sử dụng constructor to initialize thuộc tính file new CUploadedFile($names, $tmp_names, $types, $sizes, $errors);

Do đó chúng ta có thể làm điều này:

public ValidatorTest extends CTestCase{ 

    public $testFile = array(
     'name'=>'yii-1.1.0-validator-cheatsheet.pdf', 
     'tmp_name'=>'/private/var/tmp/phpvVRwKT', 
     'type'=>'application/pdf', 
     'size'=>100, 
     'error'=>0 
    ); 

    public function testValidators() 
    { 
     $testUpload = new TestUploadForm; 

     $testUpload->test = new CUploadedFile($this->testFile['name'],$this->testFile['tmp_name'],$this->testFile['type'],$this->testFile['size'],$this->testFile['error']); 
     $this->assertTrue($testUpload->validate()); 

     $errors= $testUpload->errors; 
     $this->assertEmpty($errors); 
    } 
} 

Các CFileValidator đưa vào tài khoản file extension for determining type, vì vậy để kiểm tra xác nhận của bạn, bạn sẽ phải tiếp tục thay đổi tên của $testFile, tức là $testFile['name']='correctname.rar'.

Vì vậy, cuối cùng chúng tôi không thực sự cần một tệp ở bất kỳ đâu, chỉ thông tin của tệp là đủ để kiểm tra.

Các vấn đề liên quan