When unit-testing objects which have a composition relationship with another object (a "has-a" relationship), as I understand it, you can only really mock the composed objects if you are using dependency injection of some sort. Hence, code of the following kind make unit-testing very difficult and might therefore be considered a bad thing:
<?php
class aSampleClass {
private $dependency;
public function __construct() {
$this->dependency = new otherClass;
}
}
This toy example is easily converted to using dependency injection by passing an instance of an otherClass
object as a parameter to the constructor, but that's not always the case. Is object composition of the above form (where the "new" operator is used directly in a class implementation) a bad thing? Should you always try and write a class so that it can be fully tested in isolation of its associations?
Using dependency injection seems to run aground for me when you are using simple Value objects (in the parlance of domain-driven design) such as a date, or a money object. In those cases, it just seems to make sense to directly instantiate the Value object in question. For instance:
<?php
class anotherSampleClass {
public function getTimeDifferencePhrase() {
$now = new date_Time;
$then = new date_Time(time()-60*60*24);
return $now->relativeTimePhrase($then);
}
}
Surely, in this example, it makes more sense for the unit tests of anotherSampleClass
to also exercise the implementation of the date_Time
objects rather than trying to use mock objects or test doubles.
Thoughts?