php - Refactoring of model for testing purpose -


i want refactor model can write unit test it. have dependencies. can point me in right direction how can remove these dependencies?

class customer {     public function save(array $data, $id = null)     {         // create or update         if (empty($id)) {             $customer = new \entities\customer();         } else {             $customer = $this->findbyid((int) $id);         }          $birthday = new datetime();         list($day, $month, $year) = explode("/", $data['birthday']);         $birthday->setdate($year, $month, $day);          $customer->setfirstname($data['firstname']);         $customer->setlastname($data['lastname']);         $customer->setcompany($data['company']);         $languagemodel = new application_model_language();         $customer->setlanguage($languagemodel->findbyid($data['language']));         $resellershopmodel = new application_model_resellershop();         $customer->setresellershop($resellershopmodel->findbyid($data['resellershop']));         $customer->setemail($data['email']);         $customer->setphone($data['phone']);         $customer->setgender($data['gender']);         $customer->setbirthday($birthday);         $customer->settype($data['type']);         $customersectormodel = new application_model_customersector();         $customer->setsector($customersectormodel->findbyid($data['sector']));         $customerreferencemodel = new application_model_customerreference();         $customer->setreference($customerreferencemodel->findbyid($data['reference']));         if (isset($data['password'])) {             $customer->setpassword($this->_hashpassword($data['password']));         }          return $customer;     } } 

i guess dependencies constructor calls in function body. out of mind there 3 ways replace them in unit test:

  1. create mock library different classes implemented, , run test include mock library instead of real modules.
  2. add set of default parameters external classes function declaration. in end new function declaration public function save(array $data, $id = null, $newcustomer=\entities\customer(), $newlangmodel = application_model_language, ...). in function body use variables create actual objects, $customer = new $newcustomer(). in test code can override every depended class mock class.
  3. you not add parameter every class, create 2 factories: 1 creates current objects, , 1 creates mock objects. inside of function request new objects factory.

    this approach useful if there many different places construction should intercepted. if there 1 function should changed, factory over-engineering.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -