【问题标题】:CakePHP's Mocking model not working as expectedCakePHP 的 Mocking 模型未按预期工作
【发布时间】:2014-01-28 14:13:22
【问题描述】:

我正在尝试用 cakePHP 编写我的第一个单元测试。 我想尝试以下操作:

public function joinLobby($userId = null, $lobbyId = null) {
    // json webservice layout
    $this->layout = 'ajax';

    if (!$userId || !$lobbyId) {
        throw new CakeException(__('Paramter(s) missing'));
    }
    if (!$this->Lobby->exists($lobbyId)) {
        throw new CakeException(__('Invalid lobby supplied'));
    }
    if (!$this->User->exists($userId)) {
        throw new CakeException(__('Invalid user supplied'));
    }

    $this->__addUsersToLobby(array($userId), $lobbyId);
}

到目前为止,我的测试用例是这样的:

public function testShouldNotAddNonExistentUserToLobby() {
    $this->LobbiesController = $this->generate('Lobbies', array(
        'methods' => array(
            'joinLobby',
            '__addUsersToLobby'
        ),
        'models' => array(
            'Lobby',
            'User'
        )
    ));
    $this->LobbiesController->Lobby->expects($this->any())->method('exists')->will($this->returnValue(true));
    $this->LobbiesController->User->expects($this->once())->method('exists')->will($this->returnValue(false));
    $this->LobbiesController->expects($this->never())->method('__addUsersToLobby');
    $this->testAction('Lobbies/joinLobby/1/1');
}

当我运行测试时,我得到了这个:

UsersLobbiesControllerTest::testShouldNotAddNonExistentUserToLobby 方法名称的预期失败等于调用 1 次。 方法预期调用1次,实际调用0次。

让测试通过的唯一方法是将“$this->once()”更改为“$this->any()”或“$this->never()”。

有什么帮助吗?? 提前致谢!

【问题讨论】:

    标签: php unit-testing cakephp testing phpunit


    【解决方案1】:

    我终于成功了。 问题是我在模拟我正在测试的同一个函数,所以它实际上并没有被调用。因此,没有执行调用其他函数的代码。 从 'methods' 数组中移除 'joinLobby' 就成功了。

    干杯

    【讨论】:

      猜你喜欢
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多