CakePHP 2.4模拟模型中的方法

时间:2013-11-15 16:33:45

标签: unit-testing cakephp testing mocking cakephp-2.4

我想测试一个模型,对于其中一个测试,我想模拟我正在测试的模型的方法。所以我不测试控制器,我不想替换整个模型,只是我测试的同一模型的一种方法。

原因是此模型方法调用文件上载处理程序。此功能已在其他地方测试过。

我现在正在做的是: 我测试模型'内容'。在那里我测试它的方法'addTeaser',它调用'sendTeaser'。 所以我想模拟sendTeaser并假设成功回答sendTeaser方法,同时测试addTeaser。

看起来像这样:

    $model = $this->getMock('Content', array('sendTeaser'));
    $model->expects($this->any())
    ->method('sendTeaser')
    ->will($this->returnValue(array('ver' => ROOT.DS.APP_DIR.DS.'webroot/img/teaser/5/555_ver.jpg')));


    $data = array(
        'Content' => array(
            'objnbr' => '555',
            'name' => '',
             ...
            )
        )
    );
    $result = $model->addTeaser($data);
    $expected = true;
    $this->assertEquals($expected, $result);

当我让我的测试运行时,我得到一个错误,即方法'sendTeaser'中的模型没有被正确调用。嘿!不应该叫它!我嘲笑这个方法! .....不是吗?

模拟方法的正确语法是什么?

一如既往地感谢您的帮助!

Calamity Jane

编辑: 以下是我的模型的相关代码:

    App::uses('AppModel', 'Model');
    /**
    * Content Model
    *
    * @property Category $Category
    */
    class Content extends AppModel {

    public $dateipfad = '';
    public $fileName = '';
    public $errormessage = '';
    public $types = array(
        'sqr' => 'square - more or less squarish',
        'hor' => 'horizontal - clearly wider than high',
        'lnd' => 'landscape - low but very wide',
        'ver' => 'column - clearly higher than wide',
    );
    public $order = "Content.id DESC";
    public $actsAs = array('Containable');

    public $validateFile = array(
        'size' => 307200,
        'type' => array('jpeg', 'jpg'),
    );


    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $hasMany = array(
        'CategoriesContent' => array(
        'className' => 'CategoriesContent',
        ),
        'ContentsTag' => array(
        'className' => 'ContentsTag',
        ),
        'Description' => array(
        'className'  => 'Description',
        )
    );





    /**
    * Saves the teaser images of all formats.
    *
    * @param array $data
    *
    * @return Ambigous <Ambigous, string, boolean>
    */
    public function addTeaser($data)
    {
        $objnbr = $data['Content']['objnbr'];
        $type = $data['Content']['teaser-type'];

        if (!empty($data['Content']['teaser-img']['tmp_name'])) {
        $mFileNames = $this->sendTeaser($data, $objnbr, $type);
        }

        if (!is_array($mFileNames)) {
        $error = $mFileNames;
        //Something failed. Remove the image uploaded if any.
        $this->deleteMovedFile(WWW_ROOT.IMAGES_URL.$mFileNames);
        return $error;
        }
        return true;
    }



    /**
    * Define imagename and save the file under this name.
    *
    * Since we use Imagechache, we don't create a small version anymore.
    *
    * @param integer $objnbr
    * @param string $teasername
    *
    * @return multitype:Ambigous <string, boolean> |Ambigous <boolean, string>
    */
    public function sendTeaser($data, $objnbr, $type)
    {
        //$path = str_replace('htdocs','tmp',$_SERVER['DOCUMENT_ROOT']);
        $this->fileName = $this->getImageName($objnbr, $type);
        $oUH = $this->getUploadHandler($data['Content']['teaser-img']);
        debug($oUH);
        exit;
        $error = $oUH->handleFileUpload();
        if (empty($type))
        $type = 0;
        if ($error === 'none'){
        // Send to ImageChacheServer
        $oICC = $this->getImagecacheConnector();
        $sCacheUrl = $oICC->uploadFile($objnbr, $type, $this->fileName);
        debug($sCacheUrl);
        return array($type => $this->fileName);
        }
        return $error;
    }


    public function getUploadHandler($imgdata)
    {
        App::uses('UploadHandler', 'Lib');
        $oUH = new UploadHandler($this, $imgdata);
        return $oUH;
    }



}

将getMock更改为getMockForModel虽然没有改变输出。

2 个答案:

答案 0 :(得分:1)

我想使用@ndm CakeTestCase::getMockForModel()来强调Cake test helper class的答案

$theModel = CakeTestCase::getMockForModel('Modelname', ['theMethodToMock']);
$theModel->expects($this->once())
         ->method('theMethodToMock')
         ->will($this->returnValue('valueToReturn'));

答案 1 :(得分:-3)

$ this-&gt; getMock不是模拟的方式。你应该使用$ this-&gt; generate

我建议你阅读一本关于CakePHP unti测试的书,如:https://leanpub.com/cakephpunittesting