我对如何对构造函数进行单元测试感到有点困惑,尤其是因为它不返回任何值。
假设我有这个类:
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 assertions , 但 PHPUnit 应该有一个等价物。
关于php - 如何对不返回任何值的 php 类构造函数进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25212952/