修复可测试类的依赖注入问题,添加以下函数,或注入构造函数。
function setDependentProperty(Type $value)
{
$this->_dependency = $value;
return $this;
}
function getDependentProperty()
{
if (!isset($this->_dependency)) {
$this->_dependency = new DependencyType();
}
return $this->_dependency;
}
然后在测试中使用 Mocks
function testUseMockedService()
{
$testedItem = new ObjectToTest();
$mock = $this->getMock('Service_ToMock',
array('functionToMock')
);
$mock->expects($this->exactly(1))
->method('functionToMock')
->will($this->returnValue($valueYouWant));
$testedItem->setDependency($mock);
$returnValue = $testedItem->doStuff();
$this->assertEquals($something, $returnValue);
}
了解单元测试不是集成测试,应该非常孤立
http://www.typemock.com/unit-tests-integration-tests
了解没有“正确”的保险金额
http://www.artima.com/weblogs/viewpost.jsp?thread=204677