Hi,
First off, I’m making this topic to receive feedback on the course I’ve taken and maybe sombody can point out obstacles I have not anticipated.
I attemp to make Yii site the “TDD way”. I’m not using codeception because I will be only using unit tests and will not mock static methods, also I am going to only retrieve data from db during tests (no saving) so my environment remains the same. I have made ModelFactory which will be used throughout site to enable mocking of anything I would want to.
ModelFactory:
namespace common\components;
use Yii;
use yii\db\ActiveQuery;
class ModelFactory {
/**
* @inheritdoc
* @return ActiveQuery the newly created [[ActiveQuery]] instance.
*/
public function find($className) {
return Yii::createObject(ActiveQuery::className(), [$className]);
}
public function create($className) {
return new $className;
}
}
It is attached to config as component ‘factory’.
Example controller action (it’s just to show how I’m using factory):
public function actionUpdate($id, $idFel = null) {
$forms = $this->findModel($id);
$formElements = null;
$formValues = array();
if($idFel !== null)
$formElements = Yii::$app->factory->find(FormElements::className())->where(['id_fel' => $idFel])->one();
if($formElements === null)
$formElements = Yii::$app->factory->create(FormElements::className());
if($formElements->getIsNewRecord() === false)
$formValues = Yii::$app->factory->find(FormValues::className())->where(['id_fel' => $formElements->id_fel])->all();
if(empty($formValues))
$formValues = [Yii::$app->factory->create(FormValues::className())];
if ($forms->load(Yii::$app->request->post()) && $forms->save()) {
return $this->redirect(['view', 'id' => $forms->id_for]);
} else {
return $this->render('update', [
'forms' => $forms,
'formElements' => $formElements,
'formValues' => $formValues,
]);
}
}
Tests I have written for this method so far are not using factory to mock find results etc… so I am not providing those, anyway I think it illustrates my point.
What do you think about it?
Thanks in advance for all the input.