[英]How does one unit test function that creates objects in loop?
我一直在嘗試解耦我的依賴關系,以便可以對一個類中的函數進行單元測試,但是遇到一個問題,我有一個循環遍歷數據數組並基於數據創建新對象的函數。 新對象對數據進行自我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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.