6

我有以下上传表单模型

class TestUploadForm extends CFormModel
{
public $test;

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

我的问题是,我该如何对此进行单元测试?我试过类似的东西:

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

但是,这一直告诉我该字段尚未填写。如何正确地对扩展规则进行单元测试?

4

1 回答 1

5

我们知道 Yii 使用CUploadedFile,对于文件上传,我们必须使用它来初始化模型的文件属性。

我们可以使用构造函数来初始化文件属性new CUploadedFile($names, $tmp_names, $types, $sizes, $errors);

因此我们可以这样做:

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'.

所以最后我们在任何地方都不需要文件,只需文件的信息就足以测试。

于 2012-04-29T12:27:00.000 回答