Pregunta

Quiero probar un modelo y para una de esas pruebas que quiero burlarme de un método del modelo que estoy probando. Así que no pruebo un controlador y no quiero reemplazar un modelo completo, solo un método del mismo modelo que pruebo.

La razón es que este método modelo llama un controlador de carga de archivos. Esta característica ya está probada en otro lugar.

Lo que estoy haciendo ahora es: Prueba el modelo 'contenido'. Allí pruebe su método 'Addteaser', que llama 'SENDTEASER'. Así que quiero burlarse de Sendteaser y falsificar una respuesta exitosa del método enviado, mientras prueba Addteaser.

que se ve así:

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

Cuando dejo que mi prueba funcione, recibo un error que un modelo dentro del método 'SendteSer' no se llama correctamente. ¡Oye! ¡No debería ser llamado! Me burlé del método! ..... o no?

¿Cuál sería la sintaxis adecuada para burlarse del método?

¡Muchas gracias como siempre por ayuda!

calamity jane

Editar: Aquí está el código relevante para mi modelo:

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



}

Cambiar a GetMock a getMockFormodel no cambió la salida sin embargo.

¿Fue útil?

Solución

$ esto-> Getmock no es el camino para burlarse.Debes usar $ esto-> generar

Le recomendaría que lea un libro sobre las pruebas de CakePHP UNTI, como esta: https://leanpub.com/cakephpunistesting

Otros consejos

Me gustaría enfatizar la respuesta de @ndm usando Clase de la prueba de la prueba de pastel CakeTestCase::getMockForModel()

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top