我一直试图解耦依赖项,以便在类中对函数进行单元测试,但我遇到了一个问题,即我有一个函数在数据数组中循环,并根据数据创建新对象。新对象对数据执行自己的INSERT
。
我该如何编写这个函数,以便模拟要在循环中创建的对象?
public function createObjects($array_of_data)
{
$new_objects = [];
foreach($array_of_data as $data)
{
//do some stuff with the data
$new_object = new newObject($data);
$new_object->saveToDB();
$new_objects[] = $new_object;
}
return $new_objects;
}
我建议创建一个新的工厂类,将该类注入createObjects()
方法(或通过该类的构造函数,或通过setter方法),然后在测试createObjects()
时嘲笑该工厂。
下面是一个简单的例子。一定要注意YourClass::createObjects()
方法中的FactoryInterface
类型提示,这使得所有这些都成为可能:
interface FactoryInterface
{
public function createObject($data);
}
class ObjectFactory implements FactoryInterface
{
public function createObject($data)
{
return new newObject($data);
}
}
class YourClass
{
public function createObjects($array_of_data, FactoryInterface $objectFactory)
{
$new_objects = [];
foreach ($array_of_data as $data) {
$new_objects[] = $objectFactory->createObject($data);
}
return $new_objects;
}
}
class MockObjectFactory implements FactoryInterface
{
public function createObject($data)
{
// Here, you can return a mocked newObject rather than an actual newObject
}
}
class YourClassTest extends PHPUnit_Framework_TestCase
{
public function testCreateObjects()
{
$classUnderTest = new YourClass();
$new_objects = $classUnderTest->createObjects(
[1, 2, 3], // Your object initialization data.
new MockObjectFactory()
);
// Perform assertions on $new_objects
}
}