我对如何对构造函数进行单元测试有点困惑,特别是因为它没有返回值。
假设我有这样一个类:
class MyClass {
/** @var array */
public $registered_items;
/**
* Register all of the items upon instantiation
*
* @param array $myArrayOfItems an array of objects
*/
public function __construct($myArrayOfItems) {
foreach($myArrayOfItems as $myItem) {
$this->registerItem($myItem);
}
}
/**
* Register a single item
*
* @param object $item a single item with properties 'slug' and 'data'
*/
private function registerItem($item) {
$this->registered_items[$item->slug] = $item->data;
}
}
显然这是有点做作和难以置信的简单,但这是为了问题的缘故。=)
我该如何为构造函数写单元测试呢?
附加问题:我认为在这种情况下不需要registerItem()
的单元测试,这是对的吗?
编辑
如果我重构以从构造函数中删除逻辑会怎么样?在这种情况下,我如何测试registerItem()
?
class MyClass {
/** @var array */
public $registered_items;
public function __construct() {
// Nothing at the moment
}
/**
* Register all of the items
*
* @param array $myArrayOfItems an array of objects
*/
public function registerItem($myArrayOfItems) {
foreach($myArrayOfItems as $item) {
$this->registered_items[$item->slug] = $item->data;
}
}
}
添加一个查找注册项的方法。
class MyClass {
...
/**
* Returns a registered item
*
* @param string $slug unique slug of the item to retrieve
* @return object the matching registered item or null
*/
public function getRegisteredItem($slug) {
return isset($this->registered_items[$slug]) ? $this->registered_items[$slug] : null;
}
}
然后检查测试中传递给构造函数的每个项是否已注册。
class MyClassTest {
public function testConstructorRegistersItems() {
$item = new Item('slug');
$fixture = new MyClass(array($item));
assertThat($fixture->getRegisteredItem('slug'), identicalTo($item));
}
}
注意:我使用Hamcrest断言,但PHPUnit应该有一个等效的
第一代码
public function testConstruct{
$arrayOfItems = your array;
$myClass = new MyClass($arrayOfItems);
foreach($arrayOfItems as $myItem) {
$expected_registered_items[$item->slug] = $item->data;
}
$this->assertEquals($expected_registered_items, $myClass->registered_items);
}