CakePhp 2.4 издевающийся способ в модели
-
20-12-2019 - |
Вопрос
Я хочу проверить модель, и для одного из тех тестов, которые я хочу издеваться над способом модели, которую я тестирую. Поэтому я не проверю контроллер, и я не хочу заменить целую модель, только один метод того же модели, которую я проверю.
Причина в том, что этот метод модели вызывает обработчик загрузки файла. Эта функция уже проверена в другом месте.
Что я сейчас делаю: Я проверю модель «Контент». Там я проверю его метод «Addteaser», который вызывает «SendSeaser». Поэтому я хочу издеваться от SendSeaser и подделать успешный ответ метода 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);
.
Когда я позволю моим тестированию, я получаю ошибку, что модель в методе «SendSeaser» не вызывается правильно. Привет! Это не должно называться! Я издевался на метод! ..... или нет?
Какой будет правильный синтаксис для издевания метода?
Большое спасибо как всегда для помощи!
Никакого джейн
Редактировать: Вот соответствующий код для моей модели:
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 не изменил вывод, хотя.
Решение
$ this-> getmock не так, чтобы издеваться.Вы должны использовать $ this-> generate
Я бы побудил вас читать книгу о CakePhp unti Testing, как это: https://leanpub.com/cakephpunittest
/ a>
Другие советы
Я хотел бы подчеркнуть ответ от @ndm , используя Cake Test Helper Class CakeTestCase::getMockForModel()
$theModel = CakeTestCase::getMockForModel('Modelname', ['theMethodToMock']);
$theModel->expects($this->once())
->method('theMethodToMock')
->will($this->returnValue('valueToReturn'));
.