对于如何对构造函数进行单元测试,我有点困惑,特别是因为它不返回值。
假设我有这门课:
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;
}
}
}发布于 2014-08-09 20:06:48
添加一个方法来查找已注册的项。
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应该有一个等价的。
https://stackoverflow.com/questions/25212952
复制相似问题