我有这样的类结构:
class A {
public someFunction() {
$objectB = new B();
$result = $objectB->getResult();
return $result;
}
}
我正在编写属于班级someFunction()
的{{1}}的单元测试。但是,它取决于班级A
。我可以模拟B
但是如何解决对B类的依赖?我想自动模拟课程someFunction()
。
答案 0 :(得分:4)
使用依赖注入:提供一个设置B对象的方法,或者将b对象可选地传递给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;
}
}
答案 1 :(得分:1)
依赖注入的另一种可能性是重构为“init”方法,即:
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();
}
}
通过此实现,“A”的子类可以覆盖“initB”来更改依赖关系,使用“PHPUnit_Framework_TestCase :: getMock()”生成的A的模拟可以定义方法的固定返回值,而不依赖于功能setter(或者你可以省略setter)。