I have a class structure like this:
class A {
public someFunction() {
$objectB = new B();
$result = $objectB->getResult();
return $result;
}
}
I am writing the unit test for someFunction()
that belongs to class A
. However, it depends on class B
. I can mock someFunction()
but how can I resolve the dependency on class B? I want to mock class B
automatically.
Use dependency injection: either provide a method to set the B object, or pass the b object optionally to someFunction()
.
class A {
public function someFunction() {
$objectB = new B();
$result = $objectB->getResult();
return $result;
}
}
class A {
public function someFunction($objectB = null) {
if ($objectB == null) { $objectB = new B(); }
$result = $objectB->getResult();
return $result;
}
}
class A {
protected $b;
public function __construct() {
$this->b = new B();
}
public function setB($b) {
$this->b = $b;
}
public function someFunction() {
$result = $this->b->getResult();
return $result;
}
}
Another possibility for dependency injection is to refactor to an "init" method, i.e.:
class A
{
function setB ( B $b = null )
{
$this->b = ( !is_null($b) ? $b
$this->initB()
);
}
function initB ( )
{
return new B();
}
function someMethod ( )
{
return $this->b->getResult();
}
}
With this implementation, subclasses of "A" can override "initB" to change the dependency and a mock of A generated with "PHPUnit_Framework_TestCase::getMock()" can define a canned return value for the method without relying on the functionality of the setter (or you can omit the setter).