【问题标题】:CakePHP testing user model with parentNode() methodCakePHP 使用 parentNode() 方法测试用户模型
【发布时间】:2013-08-30 13:54:23
【问题描述】:

我正在尝试学习如何进行一般的单元测试,但具体来说,我正在处理的项目是使用 CakePHP 构建的。我的用户模型中有这个 parentNode() 方法,直接取自 Simple Acl Controlled Application 教程。

public function parentNode() {
    if (!$this->id && empty($this->data)) {
        return null;
    }
    if (isset($this->data['User']['group_id'])) {
        $groupId = $this->data['User']['group_id'];
    } else {
        $groupId = $this->field('group_id');
    }
    if (!$groupId) {
        return null; // not tested
    } else {
        return array('Group' => array('id' => $groupId));
    }
}

我写了以下测试

public function testParentNodeHasNoUserDataOrId() {
    unset($this->User->id);
    unset($this->User->data);
    $this->assertNull($this->User->parentNode());
}

public function testParentNodeWithGroupIDInUserData() {
    $this->User->data['User']['group_id'] = 1;
    $this->assertEquals(array('Group'=>array('id'=>1)),$this->User->parentNode());
}

public function testParentNodeWithoutGroupIDInUserData() {
    $this->User->id = 1;
    unset($this->User->data['User']['group_id']);
    $this->assertEquals(array('Group'=>array('id'=>1)), $this->User->parentNode());
}

而且它们似乎都有效。然而,我的代码覆盖率报告显示我没有在 if(!$groupId) 块中测试 return null;。我不知道如何测试那条线。

据我所知,它永远不会执行。如果我的用户模型没有 id 并且没有数据,它会在第一个 if 块中返回 null。如果我作弊并给用户一些假数据$this->field('group_id') 仍然返回第 1 组(我认为它是 should return false instead 但它没有)

那么当单元测试时你必须测试所有东西吗?我如何测试return null if(!$groupId)?如果有永远不会执行的代码,我应该删除它吗?

谢谢!

【问题讨论】:

    标签: php unit-testing cakephp phpunit cakephp-2.3


    【解决方案1】:

    我想出了如何通过以下测试来测试“不可能”的场景

    public function testParentNodeWhenUserHasNoGroupId() {
        $this->User->id = 1;
        $user = $this->User->read();
        $user['User']['group_id'] = 0;
        $this->User->save($user);
        $this->assertNull($this->User->parentNode());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      相关资源
      最近更新 更多