Yii-模型单元测试上传表单 [英] Yii - Model Unittesting an upload form

查看:89
本文介绍了Yii-模型单元测试上传表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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);
}

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

解决方案

我们知道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 考虑了 解决方案

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-模型单元测试上传表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆