【问题标题】:Yii - Model Unittesting an upload formYii - 模型单元测试上传表单
【发布时间】:2012-05-09 08:40:26
【问题描述】:

我有以下上传表单模型

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。 document 字段应该是什么?为什么没有设置 $test 字段?
  • document 字段是字符串吗?
  • 糟糕,复制粘贴错误。测试 = 文档。
  • 好的。将尝试通过解决方案回复您
  • 你能告诉我phpunit的确切输出吗?

标签: yii phpunit


【解决方案1】:

我们知道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'

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

【讨论】:

    猜你喜欢
    • 2014-05-10
    • 2012-06-15
    • 2014-06-20
    • 2015-01-16
    • 1970-01-01
    • 2013-09-28
    • 2019-06-21
    • 2015-06-24
    • 2017-12-19
    相关资源
    最近更新 更多