因此,我们可以这样做: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); }} CFileValidator 考虑了用于确定类型的文件扩展名,因此要测试验证器,您必须不断更改$testFile的名称,即$testFile['name']='correctname.rar'. 因此,最后我们真的不需要在任何地方放置文件,只需文件的信息就足以进行测试.I have the following uploadform modelclass TestUploadForm extends CFormModel{public $test;public function rules(){ return array( array(test, 'file', 'types' => 'zip, rar'), );}My Question is, how can I unit test this? I've tried something like: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);}However, That keeps telling me the field hasn't been filled in. How can I properly unit test the extension rules? 解决方案 As we know that Yii uses CUploadedFile, for file uploads, we have to use it to initialize the file attribute of the model.We can use the constructor to initialize the file attribute new CUploadedFile($names, $tmp_names, $types, $sizes, $errors);Hence we can do this: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); }}The CFileValidator takes into account the file extension for determining type, so to test your validator you'll have to keep changing the name of the $testFile, i.e $testFile['name']='correctname.rar'.So finally we do not really need a file anywhere, just the info of the file is enough to test. 这篇关于Yii-模型单元测试上传表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-22 10:23