unit testing - Instance mocking and implicit constructors -


i trying use tdd on class manages database connections.

  • i developing away network databases available
  • i want test classes not mess real connections, sqlite :memory:
  • i may want test connections in platform-independent manner (eg. exchanging pdo objects mysqli objects etc). databases not mysql, sqlserver.

essentially want this:

class connectionmanager {     ...     public function getconnection($name) {         $params = $this->lookup($name);         return new \pdo($params['spec'], $params['username'], $params['password']);     } } 

and in test runner:

class connectionmanagertest extends \phpunit_framework_testcase {     public function testgetconnection() {         $cxn = new connectionmanager();          $this->assertnotnull($cxn->getconnection('test')); // or whatever     } } 

somehow use mock of pdo class. option add explicit parameter test class constructor or 1 of methods? i've tried using 'instance mocking' per mockery documentation, i'm using autoloading results in 'fatal error cannot redeclare class' (duh).

i'd prefer not pollute contracts code purely used in testing, option?

thanks help

this looks case dependency injection you. there many articles on web describing technique (here wikipedia overview), , previous stack overflow answer gives concise explanation of technique (the example in java, should explain pattern , transferable language enough).

your point 'not wanting pollute code contracts purely used testing' interesting one. think find, more experience tdd, writing code designed testable, , writing clean code, 2 sides of same coin. 1 of subtle powers of tdd (when practiced correctly) leads towards good, clean design can grown application. following approach puts testing @ heart of how design code, designing code client's perspective, leads cleaner interfaces different components in code , makes code uses these interfaces cleaner.

dependency injection common technique applied when following tdd, , great illustration of these points. on 1 hand effective testing because allows swap components @ test time, can avoid having call databases, mock , verify interactions between components , on. however, supports design because leads towards low-coupled , flexible design (for example, if dependency injecting access database, makes simple change data source database other technology).


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -