php - 如何对不返回任何值的 php 类构造函数进行单元测试

标签 php unit-testing testing phpunit codeception

我对如何对构造函数进行单元测试感到有点困惑,尤其是因为它不返回任何值。

假设我有这个类:

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/

相关文章:

php - 在 PHP 中锁定 MySQL INNODB 行

python - 模拟补丁多个

javascript - 我应该如何衡量 JS 的单元测试覆盖率?我不能满足于 jscoverage

c++ - VS2012:单元测试错误:Assert::AreEqual(object, object) 无效

go - 是否有众所周知的四元数测试向量?惩罚幼稚实现的已知测试代码?

php - Laravel 延迟加载和分页

php - 大流量会导致CSS故障吗?

c++ - 如何在 Google Test 中为一个夹具运行多个测试用例?

javascript - var 未在 Angular Testing 中定义

php - MySQL:WHERE 值大于 Min 且小于 Max