Yii - 模型单元测试上传表格

时间:2012-04-29 06:44:08

标签: yii phpunit

我有以下uploadform模型

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

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

1 个答案:

答案 0 :(得分:5)

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

我们可以使用constructor to initialize文件属性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会考虑file extension for determining type,因此要测试验证者,您必须不断更改$testFile的名称,即$testFile['name']='correctname.rar'

所以最后我们并不需要任何地方的文件,只需要文件的信息即可进行测试。